Ajax POST Request

On this page we demonstrate how to use just plain JavaScript to perform an Ajax POST request, without resorting to a library like jQuery.

In contrast to a GET request, which can only pass a relatively small amount of data in the URL, a POST request can accommodate a large amount of data since it is passed in the body of the request. A POST request is used when the purpose is to make changes on the server, such as entry into a database.

For example, you could use a form like the following to enter a new book into a database. It includes fields for title, author, and publication date:

Example: Ajax POST Request

Ajax POST Request Handler

The JavaScript displayed below shows how to handle the Ajax POST request and response when a button is clicked:

// button onclick handler
document.getElementById('demoPost').onclick = function() {
    // get references to form elements
    var title = this.form.elements.title.value;
    var first = this.form.elements.firstName.value;
    var last = this.form.elements.lastName.value;
    var date = this.form.elements.pubDate.value;
    
    // callback object defines methods for handling response (success and failure)
    var callback = {
        success: function(req) {
            document.getElementById('result').innerHTML = req.responseText;
        },
        failure: function(req) {
            document.getElementById('result').innerHTML = 'An error has occurred.';
        }
    }
    
    // encode form data
    var data = dw_encodeVars( {title:title, firstName:first, lastName:last, pubDate:date} );
    
    // MIME type for request
    var dataType = 'application/x-www-form-urlencoded';
    
    // arguments: url, callback object, request method, data to post, data type
    dw_makeXHRRequest( 'post.php', callback, 'POST', data, dataType );
}

First, we get references to form elements.[1] Then we define a callback object which includes success and failure methods where you specify what you would like to do when the request is returned or a problem is encountered. The callback object is passed to the dw_makeXHRRequest function which is set up to invoke the success and failure methods, passing the XMLHttpRequest object it creates.

Next, we encode the data using the dw_encodeVars function. As in the GET example, we use form element names as property names in the object, to be consistent with regular form submission. Then we specify an appropriate dataType for the data we are submitting, which is 'application/x-www-form-urlencoded'. The dw_makeXHRRequest function uses this to set a Content-Type header.

Finally, we invoke the dw_makeXHRRequest function, passing the URL we are posting to, the callback object, the method (POST), the data we have encoded, and the data type.

The download file includes a working example.

PHP Access to Values Sent in Ajax Post

When you use the data type 'application/x-www-form-urlencoded' for your Ajax Post request, PHP has access to the values the same as with the regular form submission. So, for example, PHP can access the entry in the title field as follows:

echo $_POST['title'];

Now that you know how to access the values passed from JavaScript, you can use this knowledge to build a database query or other functionality of your choice. Happy coding!