Ajax GET Request

On this page we demonstrate how to use the JavaScript provided earlier to perform an Ajax GET request. The JavaScript is very lightweight and uses the XMLHttpRequest object directly rather than relying on jQuery or any other library.

GET requests are used to query the server rather than make changes on the server. They are fast, efficient, and ideal for situations where only a small amount of data is involved and security is not an issue.[1]

For example, suppose you want to query a book collection database for books by David Flanagan. You could do so using a form like the following:

Example: Ajax GET Request

Data being passed to the server using the GET method is included in the URL in name-value pairs in the query string. The data must be properly encoded, with spaces and other special characters converted. With the above form, if its action is lookup.php and you submit, the data is encoded in the URL as follows:

lookup.php?firstName=David&lastName=Flanagan

When using Ajax rather than submitting the form, the encoding is done in JavaScript using the built-in encodeURIComponent function. Our JavaScript provides a function for that purpose. Read on to see how it's used.

Ajax GET Request Handler

The function displayed and described below is assigned to a button's onclick property. It initiates the Ajax request and handles the response:

// handle button onclick 
document.getElementById('demoGet').onclick = function() {
    
    // get references to form elements
    var first = this.form.elements.firstName.value;
    // another way to get reference
    var last = this.form['elements']['lastName'].value;
    
    // encode data
    var data = dw_encodeVars( {firstName:first, lastName:last} );
    
    // callback object with functions for success and failure of request
    var callback = {
        success: function(req) {
            alert(req.responseText);
        },
        failure: function(req) {
            alert('Error encountered');
        }
    }
    
    // call function to initiate request and handle response
    // with form data appended to url query string
    dw_makeXHRRequest('get.php?' + data, callback);
}

First, we get references to the form elements.[2] Then we encode the data using the dw_encodeVars function described earlier. Notice that the object passed to dw_encodeVars uses form element names as property names and variable names as values. PHP would expect these names with a regular form submission, so we use them here to be consistent.

Next we define a callback object with success and failure properties. These provide the methods for handling success and failure of the request. Notice how the success function accesses the Ajax response using the responseText property of the req object passed to it from the dw_makeXHRRequest function. This example just displays the response in an alert to provide a starting point for crafting a response suitable to your purposes.

Finally, at the end of the function, we call dw_makeXHRRequest to initiate the request:

// encoded data appended to url query string
dw_makeXHRRequest('get.php?' + data, callback);

The dw_makeXHRRequest function call includes the URL and callback parameters. The data we have encoded is added to the URL as required for a GET request. The dw_makeXHRRequest function is set up to invoke the success and failure methods of the callback object.

PHP Access to Values Sent with Ajax

PHP is able to access the data sent in an Ajax GET request just as with a regular form submission. For example, the value entered in the lastName field is output as follows:

echo $_GET['lastName'];

Armed with the means of access to the data submitted, you can build a database query or perform other tasks on the server with the values passed from JavaScript.

Although the online examples are not functional, those in the download file are.


  1. There are limits on the amount of data that can be passed in a GET request. The exact limits vary depending upon server, client, and proxy, but it is safest not to rely on a length greater than 255 characters. Security is an issue because the data is passed in the URL in plain text. ^
  2. Find out more about Obtaining References to Form Elements. ^