Jschool

AJAX

AJAX allows your JavaScript code to communicate with servers over the internet, performing HTTP requests with them, and retrieving any data that they may send back - meaning you can use data sent from servers within your web page interactively, no page refreshing needed...

Unsure of what a HTTP request is? Find out more about them here, and specifically more about what they actually contain here.

A simple AJAX request example

AJAX allow HTTP requests (of any type - POST, GET, etc.) to be carried out 'in the background' asynchronously in JavaScript, and their response data (along with response code) to be returned to your JavaScript - meaning that you can then use the data you've received back - for example by formatting it into HTML and adding it to the web page. This means that you can then display new data that you've retrieved from a web server to a user, without them having to refresh the page themselves, as an example.

An AJAX request is to be created by creating a XMLHttpRequest object, and then having a request URL and request method set on it using the .open() method. The request can then be sent with the .send() method. In POST requests, POST data can also be added using the .send(myData) method, passing in your encoded POST data as a parameter (where myData is in the example).

The response is handed to a 'callback' function when complete, and this function firstly needs to check if the request was completed successfully by looking at its status code (the .statusCode property, containing a Number, which has the standard HTTP response code to state how the request was completed), before then using the .responseText to get the raw response data that the server has returned (in the case that the request was a success).

A simple example of an AJAX POST request is shown below...

                
// create a new AJAX request
var ajaxRequest = new XMLHttpRequest();

// set the API endpoint URL to carry out the request on...
var apiUrl = "http://my-cool-api.com/api/endpoint";

// set the request method in a string (i.e. POST, GET, DELETE, etc.)
var requestType = "POST";

// set the request data to POST too (if it's a POST request)...
var postData = "data=Hello%20World";

// set the AJAX request type and URL to the variables we set up previously
ajaxRequest.open(requestType, apiUrl, true);

// add an anonymous 'callback' function to execute once the request is complete...
ajaxRequest.onreadystatechange = function () {

    if (ajaxRequest.readyState != 4 || ajaxRequest.status != 200) {
        /* an error occurred -
        the request has not been carried out correctly */

        // let's log the failure...
        console.log("AJAX Request failed with status " + String(ajaxRequest.status));

        // nothing we can do... give up and return.
        return;
    }


    /* if we've reached this point we can be sure the request
        completed properly, let's log that, and the data we got back... */

    // log the success and the status of the request...
    console.log("AJAX Request succeeded with status " + String(ajaxRequest.status));

    // and log the data we received back...
    console.log("Received data: " + String(ajaxRequest.responseText));

};

// send the POST data that we prepared earlier
ajaxRequest.send(postData);

                
            

200 is the standard response status code for a successful HTTP request - meaning that it's worked as expected. You can view a full list of possible HTTP response codes here, and include as many as you need to handle within your callback function.
Post data should be URL Encoded before being sent.