Captain's Universe Home
Captain's Universe Home
Cosmic Ray Muon DetectorTeleGarden Pages
Time on MarsBryophyllum Plants
Jupiter Radio AstronomyAncient Pages
Salzburg Tourist GuideEarth Magnetometer
  H O M E     AJAX & MORE     LINUX & MORE     RTAI     XENOMAI     ADEOS IPIPE      
    JAVA & BROWSERS     *NIX     ELECTRONICS     REVIEWS     ARTEMIA     FAIRY SHRIMP      


AJAX Form POST/GET - HTML Form Submit with AJAX/Javascript Example/Tutorial

Also see:
AJAX/Javascript Form POST Request
AJAX/Javascript XML Tips & Tricks
AJAX/Javascript XML Processing Example/Tutorial

Mark, a visitor of captain.at was so kind so send in some code improvement:
see it here

UPDATE: In order to avoid a syntax error in Firefox, if the returned content is NOT valid XML, use the overrideMimeType method to set the content-type.
         	// set type accordingly to anticipated content type
            //http_request.overrideMimeType('text/xml');
            http_request.overrideMimeType('text/html');


AJAX is the new hype in HTML/Javascript, since Google came up with their nifty GMAIL application. AJAX allows to write web-applications without reloading/refreshing the page on user interaction (e.g. posting data to a server-side script). The traditional way of processing HTML forms was to submit them to the server, the server processed the data and sent a response. The drawback of this method is that the page was reloaded in the browser.



With AJAX the browser page is not reloading, but the data is just sent to the server for processing. The server saves the data or calculates something and sends back the answer. The AJAX javascript either displays the answer (page) or does some action depending on the answer.

This example demonstrates a simple AJAX javascript for sending a complete HTML form to the server and displaying the response. The javascript automatically gets all form elements - the server-response is displayed in a "span" - the server-side script is a simple PHP script to display the contents of the $_GET global variable.



UPDATE:
I've updated the form - now it also works with a normal submit button and also when the user just presses enter!

Test the whole hack here:






0 1
1 2 3 4 5


Server-Response:


The javascript automatically sends ALL checkboxes, so you don't have to care about this server-side :-)



index.html:
<script type="text/javascript" language="javascript">
   var http_request = false;
   function makeRequest(url, parameters) {
      http_request = false;
      if (window.XMLHttpRequest) { // Mozilla, Safari,...
         http_request = new XMLHttpRequest();
         if (http_request.overrideMimeType) {
         	// set type accordingly to anticipated content type
            //http_request.overrideMimeType('text/xml');
            http_request.overrideMimeType('text/html');
         }
      } else if (window.ActiveXObject) { // IE
         try {
            http_request = new ActiveXObject("Msxml2.XMLHTTP");
         } catch (e) {
            try {
               http_request = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {}
         }
      }
      if (!http_request) {
         alert('Cannot create XMLHTTP instance');
         return false;
      }
      http_request.onreadystatechange = alertContents;
      http_request.open('GET', url + parameters, true);
      http_request.send(null);
   }

   function alertContents() {
      if (http_request.readyState == 4) {
         if (http_request.status == 200) {
            //alert(http_request.responseText);
            result = http_request.responseText;
            document.getElementById('myspan').innerHTML = result;            
         } else {
            alert('There was a problem with the request.');
         }
      }
   }
   
   function get(obj) {
      var getstr = "?";
      for (i=0; i<obj.childNodes.length; i++) {
         if (obj.childNodes[i].tagName == "INPUT") {
            if (obj.childNodes[i].type == "text") {
               getstr += obj.childNodes[i].name + "=" + obj.childNodes[i].value + "&";
            }
            if (obj.childNodes[i].type == "checkbox") {
               if (obj.childNodes[i].checked) {
                  getstr += obj.childNodes[i].name + "=" + obj.childNodes[i].value + "&";
               } else {
                  getstr += obj.childNodes[i].name + "=&";
               }
            }
            if (obj.childNodes[i].type == "radio") {
               if (obj.childNodes[i].checked) {
                  getstr += obj.childNodes[i].name + "=" + obj.childNodes[i].value + "&";
               }
            }
         }   
         if (obj.childNodes[i].tagName == "SELECT") {
            var sel = obj.childNodes[i];
            getstr += sel.name + "=" + sel.options[sel.selectedIndex].value + "&";
         }
         
      }
      makeRequest('get.php', getstr);
   }
</script>


<input type="button" name="button" value="GET test.html" 
   onclick="javascript:makeRequest('test.html', '');">
<br><br>
<input type="button" name="button" value="GET get.php?test=2" 
   onclick="javascript:makeRequest('get.php', '?test=2');">
<br><br>


<form action="javascript:get(document.getElementById('myform'));" name="myform" id="myform">
<input type="text" name="myfield" value="teststring"><br>
<input type="radio" name="myradio" value="0" checked> 0
<input type="radio" name="myradio" value="1"> 1<br>
<input type="checkbox" name="mycheck1" value="1"> 1
<input type="checkbox" name="mycheck2" value="2"> 2
<input type="checkbox" name="mycheck3" value="3"> 3
<input type="checkbox" name="mycheck4" value="4"> 4
<input type="checkbox" name="mycheck5" value="5"> 5
<br>
<select name="myselect">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<br>
<input type="button" name="button" value="Submit" 
   onclick="javascript:get(this.parentNode);">
<input type="submit" name="button" value="Normal Submit Button">
</form>

<br><br>
Server-Response:<br>
<span name="myspan" id="myspan"></span>

test.html
content of test.html

get.php
<?
print_r($_GET);
?>


Mark's update:
"If you're using your form in tables, the first are going to be table objects - row, cols, etc.
Instead of drilling down in for loops to find form objects, the simplest path is to use getElementsByTagName("input") instead of childNodes[i]. "
function get(obj) {
  var getstr = "?";
  for (i=0; i<obj.getElementsByTagName("input").length; i++) {
        if (obj.getElementsByTagName("input")[i].type == "text") {
           getstr += obj.getElementsByTagName("input")[i].name + "=" + 
                   obj.getElementsByTagName("input")[i].value + "&";
        }
        if (obj.getElementsByTagName("input")[i].type == "checkbox") {
           if (obj.getElementsByTagName("input")[i].checked) {
              getstr += obj.getElementsByTagName("input")[i].name + "=" + 
                   obj.getElementsByTagName("input")[i].value + "&";
           } else {
              getstr += obj.getElementsByTagName("input")[i].name + "=&";
           }
        }
        if (obj.getElementsByTagName("input")[i].type == "radio") {
           if (obj.getElementsByTagName("input")[i].checked) {
              getstr += obj.getElementsByTagName("input")[i].name + "=" + 
                   obj.getElementsByTagName("input")[i].value + "&";
           }
     }  
     if (obj.getElementsByTagName("input")[i].tagName == "SELECT") {
        var sel = obj.getElementsByTagName("input")[i];
        getstr += sel.name + "=" + sel.options[sel.selectedIndex].value + "&";
     }
     
  }
  makePOSTRequest('post.php', getstr);
}


Last-Modified: Sat, 30 Aug 2008 22:56:19 GMT

Google
 
Web www.captain.at
go to top
© 1996-2010 . All rights reserved.
No reproduction, distribution, publishing or transmission of the copyrighted materials at this site is permitted. Policy
go to top