(click anywhere to close)

[JavaScript] AJAX

category: Website | course: Advanced Javascript | difficulty:

AJAX stands for Asynchronous Javascript and XML. The last part of this name is quite misleading – you don’t need to know anything about XML to make this work. This first part of the name, however, is right on point. Whereas last chapter talked about asynchronous JavaScript mostly within the script itself, AJAX is a way of sending and receiving data without reloading the page.

Essentially, AJAX works via an object that can connect with the server to get a certain file, and has certain events you can listen for once it has established this connection (or failed to establish one).

To create an AJAX object, use

new XMLHttpRequest()

Opening a Connection

To open a connection, use the open(method, URL, async) method.

  • method: Specifies the type of request; GET or POST. More on that later.
  • URL: The URL we want to establish a link with
  • async: Whether we want this connection to be asynchronous or not. Of course we do, so just always set this to true (or omit it).
var con = new XMLHttpRequest();

Sending Requests

Once a connection has been opened, you still need to send a request if you want to get a response. How you should send this request, depends on the method you use.

The GET method is faster than POST, and can be used in most cases. To send a request, simply use send(). If you want to send arguments along with the request, add those to your URL.

var con = new XMLHttpRequest();
//No parameters
//With parameters

//This stays the same in both cases

The POST method is better if you’re sending large amounts of characters, or user input – POST has no size limitations and is more secure. To send a request, use send(string). In this case, the string contains the arguments you want to send along. If you want to send special data, however, like an HTML form, you need to specify what type of data is coming with the request (before you send it), which is done with a header

var con = new XMLHttpRequest();
con.open("POST", "someFile.php", true);
con.setRequestHeader("Content-type", "application/x-www-form-urlencoded");


Receiving Feedback

As the AJAX object is trying to get your data, it goes through several stages, which we call readyStates. These stages are:




Request not initialized


Server connection established


Request received


Processing request


Request finished and response is ready

To check when such a readyState changes, use the readystatechange event.

Once the request has reached stage 4, it either succeeded or failed. This is saved in the status property, which returns 200 if everything is fine, and 404 if the URL could not be found.

var con = new XMLHttpRequest();
 con.onreadystatechange = function() {
    if (con.readyState == 4 && con.status == 200) {
     //Do stuff, cause connection was successful!
con.open("GET", "someFile.php", true);

Receiving Data

And now, the big moment, we can do something with the received data! The responseText property holds everything that was on the page we requested. Even if the request didn’t turn out fine, we can hope for a sensible (error) message.

var con = new XMLHttpRequest();
 con.onreadystatechange = function() {
    if (con.readyState == 4 && con.status == 200) {
     	console.log(con.responseText); //Prints whatever was sent back by the server

Optionally, we can send back XML data and receive (and parse) it with the responseXML property – hence the XML in AJAX.

Now with Promises

To demonstrate the power of promises again, I just want to show you how the whole AJAX handler code could also be written using a promise.

function getURL(url) {
  return new Promise(function(resolve, reject) {
    var req = new XMLHttpRequest();
    req.open('GET', url);

    req.onload = function() {
      if (req.status == 200) {
      } else {

    // Handle network errors
    req.onerror = function() {
      reject(Error("Network Error"));

    // Make the request

//Accessing someFile.php asynchronously...
getURL('someFile.php').then(function(response) {
  console.log("Success!", response);
}, function(error) {
  console.error("Failed!", error);
[JavaScript] PromisesNo next post :(
Do you like my tutorials?
To keep this site running, donate some motivational food!
Chocolate Milk