(click anywhere to close)
OPEN MENU

[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();
con.open("GET","someFile.php",true);

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
con.open("GET","someFile.php",true);
//With parameters
con.open("GET","someFile.php?a=2&b=4",true);

//This stays the same in both cases
con.send();

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");

con.send("a=2&b=4");

Receiving Feedback

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

Readystate

Description

0

Request not initialized

1

Server connection established

2

Request received

3

Processing request

4

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);
con.send();

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) {
        resolve(req.response);
      } else {
        reject(Error(req.statusText));
      }
    };

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

    // Make the request
    req.send();
  });
}

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