Why would you need to do this? Well for instance if you were using 3rd party AJAX APIs and you wanted to capture the data from them perhaps, or maybe you just have a complex form.
Or you could use this for form validation to return errors from the server without refreshing the browser, for example, if the data already exists in a database you could let the user know.
Either way its pretty simple. Basically we just use javascript to post the form object over http to a serverside page – e.g. PHP, JSP, ASP etc…
First of lets have a look at the javascript
<script type="text/javascript"> //build a variable to store our request object var my_http_request = false;
So we’ve started our file and declared a variable to store our request, next we build the request object, unfortunately we have to cover multiple browsers because IE is non-standard:
//this function builds an object of form data and sends it over HTTP to our PHP page function buildPOSTRequest(url, parameters) { my_http_request = false; if (window.XMLHttpRequest) { // Mozilla, Safari,... my_http_request = new XMLHttpRequest(); if (my_http_request.overrideMimeType) { // set type to content type my_http_request.overrideMimeType('text/html'); } } else if (window.ActiveXObject) { // IE try { my_http_request = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { my_http_request = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {} } } if (!my_http_request) { alert('Unable to create XMLHTTP instance'); return false; }
We’ve now built our object in the DOM to store our data so the final part of this function is to send the data. Because we are posting the data we have to use setRequestHeader in order to store everything in the POST headers and for the PHP page to be able to retrieve the data.
//when status is changed display the contents back to the page if you want to my_http_request.onreadystatechange = updatedContents; //open connection to server my_http_request.open('POST', url, true); my_http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); my_http_request.setRequestHeader("Content-length", parameters.length); my_http_request.setRequestHeader("Connection", "close"); //send the data my_http_request.send(parameters); } // end buildPOSTrequest function //this function when called fetchs anything thats been outputted on post.php //It gets called as part of the buildPOSTrequest function function updatedContent() { if (my_http_request.readyState == 4) { if (my_http_request.status == 200) { result = my_http_request.responseText; //display the results from post.php back to your page document.getElementById('myObject').innerHTML = result; } else { alert('Error: couldnt access post.php.'); } } }
An extra function is added here in case you want to post back say validation issues or confirmation. Now all we do is write a function that when the form is posted or submit button is clicked it gets the data from the form and passes that to our buildPOSTRequest function.
function sendData(formName) { //build a variable to store the form data, use encodeURI to encode any random chars var postFormVars = "addressLine1=" + encodeURI( document.getElementById("addressLine1").value ) + "&addressLine2=" + encodeURI( document.getElementById("addressLine2").value ) + "&addressLine3=" + encodeURI( document.getElementById("addressLine3").value ) + "&town=" + encodeURI( document.getElementById("town").value ) + "&postcode=" + encodeURI( document.getElementById("postcode").value ); //send our data via XMLHttpRequest to post.php buildPOSTRequest('post.php', postFormVars); } </script>
And thats it, as for the HTML form, only thing to note is that the form action calls the sendData function:
<form action="javascript:sendData(document.getElementById('myform'));" name="myform" id="myform">
<table width="600" border="0" cellspacing="5" cellpadding="5">
<tr>
<td width="130">* Address Line 1: </td>
<td width="435"><input type="textfield" name="addressLine1" id="addressLine1" value=""></td>
</tr>
<tr>
<td> Address Line 2: </td>
<td><input type="textfield" name="addressLine2" id="addressLine2" value=""></td>
</tr>
<tr>
<td>Address Line 3: </td>
<td><input type="textfield" name="addressLine3" id="addressLine3" value=""></td>
</tr>
<tr>
<td>* Town: </td>
<td><input type="textfield" name="town" id="town" value=""></td>
</tr>
<tr>
<td>* Postcode: </td>
<td><input type="textfield" name="postcode" id="postcode" value=""></td>
</tr>
<tr>
<td> </td>
<td><input name="Add" value="Add" type="submit" /></td>
</tr>
</table>
</form>
<p><b>Server-Response:<b></p>
<p name="myObject" id="myObject"></p>Oh and of course the post.php page, in here you could add in your validation, check the database etc… what ever you ourput to the page (using print, echo etc…) can be then sent back to your form page and displayed without the user leaving your form page or refreshing the browser.
<?php // print everything from the POST header, normally returned as an array print_r($_POST); ?>
This content is published under the Attribution-Noncommercial-Share Alike 3.0 Unported license.
- Creating XML from PHP/ MySQL for use with SPRY
- Google Maps API part 1: Accurate Geocoding for UK Postcodes
- Google Maps API part 2: Retrieving Postcodes from your database
- Using SPRY to fetch values from a URL
- Running multiple instances of Jboss on one server.
- Upload a File Using PHP
- Adding and changing Mod JK JVM route, URI encoding and thread settings for JBoss
- Quick popup/overlay show and hide a layer with Javascript and CSS
- Joining columns/ concatenate strings in Oracle PLSQL/ MySQL
- Setting the JDK version and compiler in JBoss for JSP pages









