Posting a Form Using AJAX
Written by Cory S.N. LaViska on July 16th, 2007
Posting forms using AJAX just got a lot easier.
This function was written in an attempt to simplify posting forms via AJAX. One call will create the query string, handle posting, and output the response. The function has 3 arguments:
- formId - the ID of the form that will be posted
- script - the script that will handle the post
- resultId - the element (usually a div) that will receive output from the script
Note that the it will not post reset, button, image, or file input types.
The Function
// Uses AJAX to post formId to script and sends the output to resultId
//
// Requires formDataToQueryString() function:
// http://abeautifulsite.net/notebook_files/31/formDataToQueryString.js
//
// Note: will not post reset, button, image, and file input types
var xmlHttpReq = false;
var self = this;
if( window.XMLHttpRequest ) {
// Mozilla/Safari
self.xmlHttpReq = new XMLHttpRequest();
} else if( window.ActiveXObject ) {
// IE
self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
}
self.xmlHttpReq.open('POST', script, true);
self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
self.xmlHttpReq.onreadystatechange = function() {
if( self.xmlHttpReq.readyState == 4 ) {
document.getElementById(resultId).innerHTML = self.xmlHttpReq.responseText;
}
}
// Generate query string from form elements
var queryString = formDataToQueryString( document.getElementById(formId) );
// Send it
self.xmlHttpReq.send(queryString);
}
The function requires the formDataToQueryString() function to create a query string from the specified form element.
Example/Demo
I’ve posted a live demo so you can see the form in action. To get a better understanding of how it works, I recommend checking out the source of the demo file.
And for anyone who wants it, here is the PHP code being executed in handle_post.php:

Comments
You can be the first person to comment on this article!