Posting a Form Using AJAX

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:

Note that the it will not post reset, button, image, or file input types.

The Function

function postForm(formId, script, resultId) {
    // 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);
}

Download postForm.js

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:

<?php
echo "<pre>";
echo htmlspecialchars( print_r($_POST, true) );
echo "</pre>";
?>

Comments

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

Add a comment

Name*

Email*

Never, ever sold or spammed :)

Homepage

Comment*

Sorry, plain text only :(