Ajax Process

How AJAX Request Works with Vanilla Javascript

What is AJAX?

AJAX stands for Asynchronous JavaScript and XML. It uses XMLHttpRequest object to send & receive data to/ from Server. It can send/ receive data in different formats like Simple Text, HTML, XML or JSON. It’s Asynchronous behaviour lets refresh the data on the page without refreshing the page, so if developer wants to update portion of the page on certain event, AJAX is very useful for such a task.

Today we have verity of JavaScript frameworks which allow to send AJAX request easily with less code. But while using these frameworks developers have to include .js  framework library (i.e.: jQuery, YUI, etc.). Although it is important to know how the AJAX query works under vanilla JavaScript.

Make a Request

In this post, I tried to explain how the AJAX request works with example. At first we need to create an object of XMLHttpRequest.

var xhr = new XMLHttpRequest();

XMLHttpRequest does not support in older IE browsers like IE6 so you need to create an object of ActiveXObject. So the initialization of the object will be as below:

var xhr;

if(window.XMLHttpRequest) {    // For all other browsers
    xhr = new XMLHttpRequest();
} else {                       // For IE6 and below
    xhr = new ActiveXObject("Microsoft.XMLHTTP");
}

Except initialization, all other methods work same in all browsers. So once the object is created, we will have to  access different methods such as:

  • onreadystatechange
  • setRequestHeader
  • status
  • open
  • send
  • readyState
  • responseText

Though there are numbers of other methods available but in above pointer I have mentioned most frequent methods to be used in AJAX request.

Now we have created object and we can check status of the request. To do so we need onreadystatechange method.

xhr.onreadystatechange = function(){
    // your code to process on server response
}

// OR

xhr.onreadystatechange = ajaxRequest;

function ajaxRequest(){
    // your code to process on server response
}

As illustrated above we can directly start anonymous function against onreadystatechange method or we can write a separate function and assign it to the method.

Receiving Data from Server

Now as we have declared the object & function, we have to call opensend methods to make connection with server and to receive data from it. open method accepts three arguments.

  1. “GET” or “POST”
  2. URL of the page on server to get data
  3. Third argument defines the asynchronous way to get data
xhr.open("GET", "data.txt", true);
xhr.send("");

 Sending Data to Server

Developers are familiar with <form> methods – “GET” and “POST” – and here in above code we have used “GET” method to get data from server. And on the other hand, while sending data to server we can use “POST” method. While using “POST” method to post data, we need to set Headers as below:

xhr.open("POST", "data.txt", true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send("first-name="+ fname +"&last-name="+ lname);

 Processing Server Response

We have already defined a JavaScript function ajaxRequest to handle server response, lets see how we can use it.

function ajaxRequest(){

    // Handle error
    if(xhr.status !== 200) {
        alert("There is something wrong with server response!");
    }

    // Everything is fine and we get response
    if(xhr.readyState === 4) {
        alert(xhr.responseText);
    }

}

The full list of readyState is as below:

  • 0 (uninitialized)
  • 1 (loading)
  • 2 (loaded)
  • 3 (interactive)
  • 4 (complete)

Full Code

var xhr;

if(window.XMLHttpRequest) {    // For all other browsers
    xhr = new XMLHttpRequest();
} else {                       // For IE6 and below
    xhr = new ActiveXObject("Microsoft.XMLHTTP");
}

xhr.onreadystatechange = ajaxRequest;

function ajaxRequest(){

    // Handle error
    if(xhr.status !== 200) {
        alert("There is something wrong with server response!");
    }

    // Everything is fine and we get response
    if(xhr.readyState === 4) {
        alert(xhr.responseText);
    }

}

xhr.open("GET", "data.txt", true);
xhr.send("");

To make above code more flexible and to use globally, I have created a new function callAJAX() including entire above code and two arguments – url  and callback.

function callAJAX(url, callback) {
    ...
    // Everything is fine and we get response
    if(xhr.readyState === 4) {
        callback(xhr);
    }
    ...
}

Now we can use below code in the project to make an AJAX request. Below sample code manipulating data from data.txt file.

load("data.txt", function(xhr){
    document.getElementById("content").innerHTML = xhr.responseText;
});

Conclusion

In general, you can reduce human efforts using javascript framework to make AJAX request. But it is always good to know what is happening under the hood from debugging perspective.

Image Credit: www.w3schools.com

Web/ UI & Front-end developer based in Ahmedabad, GJ, India. Here to help/ discuss community to spread web awareness.

Leave a reply:

Your email address will not be published.