What is ajax in javascript? That's a question most web developers have asked themselves at least once in their careers. Firstly it should be pointed out that ajax doesn't have anything to do with famous cleaning product. It's a technique for doing asynchronous http requests to a web server.

Asynchronous programming

Asynchronous programming basically means that other things can be done meanwhile you're waiting for some long slow thing to finish, like for example connecting to a database on a server. Instead of completely stopping up all execution of code until the request has finished, and an answer back has been returned, other code can be run in the meantime the request in being done and the server is looking through the database. It's a clever way of doing things which can improve the performance and responsiveness of applications very much.

The technique ajax, which actually is a combination of techniques is what makes this possible in javascript (well it can be done with iframes too, but it's much messier). It enables data to be fetched with http requests out from servers, and to be loaded in directly into a page without it having to reload. By default it's restricted to only connect to your own server for security reasons, but this can easily be changed with server headers.

Ajax requests are completely asynchronous, so while the data is retrieved over the internet other code can still keep running if you want. It's also possible to send and retrieve data from a server without the user doing anything, just think about a site like facebook where new data is loaded in all the time while scrolling.

In this article we'll just focus on how to do an ajax request in its simplest form, and how to send and retrieve data from a server without the page having to reload.

First example with ajax in javascript

Below is an example of how a string from a php script can be loaded in with ajax to a site, without it having to reload.

(php)

<?php echo 'Hello there!';

(javascript)

var xhr = new XMLHttpRequest();

xhr.onreadystatechange = function () {
if (xhr.readyState === 4) { // readyState 4 means data has been retrieved
if (xhr.status === 200) { // 200 means everything went well
var p = document.getElementById('ajaxResult');
p.textContent = xhr.responseText; // Hello there!

} else { // something went wrong
console.log('Error: ' + xhr.status);
}
}
}

xhr.open('get', '/ajax/test-1/', true); // prepares the request
xhr.send(); // sends the request

First an object has to be instantiated from XMLHttpRequest and be assigned to a variable. The you set the event onreadystatechange on it for what should happen when an answer from the server is returned back. With the property readyState we can see what status the request has: 1 means the connection has been opened, 2 that headers are available, 3 loading, and 4 that it's finished and an answer has been received. The event onreadystatechange will run once for every state.

The fourth state (4) is what's interesting because then we know the request is completed and we can start processing the response. First we use an if statement to check if the status is 4, and then do next following. A request can sometimes go wrong, so therefore we must also check if the http status code is 200, which means ok. If the status code is something else like 404 something has failed like we sent the request to an invalid url or the server happens to be down. For a real project the error should probably be handled in a better way than in the example, where it's just logged out in the console.

Then it's time to use the method open. It's first argument is what request method it should use, "get" or "post". Next is the url to send to, and the third is if the request should be asynchronously or not. True means async and false not (update: synchronous requests are now deprecated).

The last thing to do is to call the method send, to actually send the ajax request.

An advanced ajax example with post and JSON

A very common thing is that you want to send a post request to a server and retrieve the response data in the form of JSON. Here's a little example on how a JSON encoded array can be retrieved from a php script, which only accepts post requests.

When post is used the content-type http header must be set to form-urlencoded. This is done with the method setRequestHeader. Then to send the parameters they're put as argument to the send method (can be as many as you want). To send parameters with get they can instead be added directly to the url.

(php)

<?php

$data = null;

if (isset($_POST['fruits']) && $_POST['fruits'] === 'all') {
$data = array('apple', 'pear', 'peach');
}

echo json_encode($data);

(javascript)

var xhr = new XMLHttpRequest();

xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
var fruits = JSON.parse(xhr.reponseText); // parses the json data

if (fruits) {
var p = document.getElementById('ajaxResult2');

fruits.forEach(function (fruit) { // loops through all fruits
p.textContent = fruit + ', ';
});
}
} else {
console.log('Error: ' + xhr.status);
}
}
};

xhr.open('post', '/ajax/test-2/', true);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.send('fruits=all');

Further reading

For some more reading about ajax there's a good reference at w3schools.com/xml/ajax_intro.asp.