AJAX Introduction with an Example


In this article, I will tell you about AJAX (Asynchronous JavaScript and XML). We will understand it with a example.

What is AJAX?

AJAX is not a programming language but a web technology. It allows you to update a web page without reloading it with the help of XMLHttpRequest (XHR) object (built-in object).
In other words we can say that AJAX helps you to retrieve data from web server to your web page asynchronously or without reloading the web page.

If you ever used web developer tools in your browser. You might have seen a network tab their. That tab shows the requests it is sending to the web server while requesting the web page. It consists of several types of requests such as JS, Img, Media, Font, WS, XHR, DOC, etc.

Working of AJAX Request

  1. First we will need to create a XMLHttpRequest (XHR) object.
  2. Using that object we will send a request to the web server to retrieve data from it.
  3. Then that web server will send us response in JSON or plaintext format.

Let's understand it through an example -

Sending a Request -

var xhr = new XMLHttpRequest();

Using the above code, we just created an XMLHttpRequest object named as xhr.

Now to send request to the server, first we will use open method of XMLHttpRequest object.

xhr.open("GET", "index.html", true);

Open method requires three parameters in it -

  1. method - Type of request GET or POST.
  2. url - location of the file on server.
  3. bool value - true for asynchronous or false for synchronous.

Now to send this request, we will use send method of XMLHttpRequest object.

xhr.send();

Now using the above three lines of code we just sent a GET request to the server to request "example.json" file.

test

Screenshot of Network tab after using send method -

test-2

To display the request's response -

Now to get the server's response, we have some property in XMLHttpRequest object.

  1. readyState - It holds the status of XMLHttpRequest sent.
  2. status - It holds the status of XMLHttpRequest object.
  3. onreadystatechange - It defines a function to be executed when the readyState property changes.

Now how will we know that the response is received and ready to be displayed.

NOTE :- When readyState is 4 and status is 200, it means the response is ready to be displayed.

Now let's create a function to display the response of the request.

function loadDoc()
{
    var xhr = new XMLHttpRequest();
    xhr.open("GET", "index.html", true);
    xhr.send();
    xhr.onreadystatechange = function()
    {
        if (this.readyState == 4 && this.status == 200)
        {
            console.log(this.responseText);
       }
    };
}

Screenshot of Developer tools after executing the function -

test-3

Using the above 13 lines of code, we sent a GET request to web server to retrieve the content of index.html page and displayed it's response in the console.

Various usage of AJAX

  • Form Autocompletion - You may have seen search fields, in where whenever you starts typing, then it starts you giving you suggestion regarding the word or sentence you're typing.

  • Comment System - Ever commented on a YouTube video? I am sure you have. As you have you have seen whenever you post a comment the video page do not reload itself, just the comment get posted under the video page. When you commented a AJAX POST request was sent to the web server to update the database.

  • Page loading - As each of us use Twitter or Instagram. What happens when you reach to the end of your homepage? Your homepage gets filled again with the older posts. How did that happen? AJAX. As you reached to the end of the page. A AJAX request was sent requesting the older posts without even reloading the page and in the response you get the content in JSON or other format which a JS script includes in your homepage.

  • Chat Room - Ever used a chat room? How we send message each other without even reloading the web page? AJAX. Whenever you send a message a AJAX request is sent to the web server updating the database about the chat history and similarly on the other(receiver) side. After every few seconds a AJAX request is sent to check if any new message was received.

  • File Upload - You have noticed that websites don't redirect you to another web page in order to upload your content on that site. It just shows a dialog or choose file field to upload the file and after the file is uploaded. A AJAX request is sent in order to move the file to the server and update the database without reloading the web page.

  • Voting and Rating System - You surely have used the upvoting system of reddit. Whenever you upvote or downvote a post on reddit. It doesn't reload the web page to update that numbers on that post. Then how it update the numbers? AJAX. A simple AJAX request is sent to web server to update the number of votes on a post in the database. You surely have the rating system on websites such as Zomato. Whenever you give rating to a restaurant, it doesn't reload the whole web page. It just sends a AJAX request and that request updates the db.

  • CAPTCHA RELOAD - Nowadays each site have a captcha to protect themselves from spam account. Whenever anyone click on reload the captcha. Whole web page does not reload, just the captcha gets reloaded. How does that happen? AJAX. By now, if you are reading all the points, you might understood what I am gonna say.

There are other tons of usage of AJAX. So, we can say we can AJAX requests everywhere. It plays a vital role in web application.

Well I hope you understood the basics of AJAX and how to send a request to the server and display the request's response.

Feel free to ask me any questions.