BlogsDope image BlogsDope

JavaScript: AJAX

July 23, 2020 JAVASCRIPT 720

AJAX stands for Asynchronous JavaScript and XML. It is a technique to exchange data between the server and the browser and to update parts of a web page without having to reload the page. When a request is sent to the server synchronously, the code blocks until a response is received, i.e., JavaScript does not execute any other script. On the contrary, asynchronous behavior allows the request to be sent on another thread, so the JavaScript can keep running other statements. When the response is received, then the relevant code runs. The XML part in the AJAX term is a bit misleading because it does not only use XML to exchange data. It also uses other data formats like JSON, etc. JSON is more common nowadays because it is lighter and a part of JavaScript. We will be using JSON as well.

Most modern browsers support an XMLHttpRequest Object, which is used to send and retrieve data from the server. There are three basics steps to send a request, i.e.,

Create an instance of XMLHttpRequest

The XMLHttpRequest object can be created using the new operator, just like other objects.

Prepare the request

The next step is to prepare a request using the open() method of the XMLHttpRequest. The syntax is open(method, destination, async). The method parameter represents the type of request, i.e., GET or POST. The second parameter represents from which location to fetch the data. It can be a URL, a file path, etc. The async parameter is optional (Default value true). It represents whether the request should be sent asynchronously(true) or synchronously(false). It is not recommended to set its value to false (send the request synchronously) as it blocks other scripts.

Ajax call

Send the request

Finally, send the request using the send() method of the XMLHttpRequest.

GET vs. POST


The difference between GET and POST is in the table below.

GET

POST

The main purpose of GET is to retrieve data from the server. It can also send data.

The main purpose of POST is to modify data on the server. It can get data too.

It is faster and simpler.

Additional request headers need to be sent first.

Limited amounts of data can be sent.

No limit on the data.

It can return a cached file or page.

It is more secure.

Data is passed in the URL.

Data is passed as an argument in the send() method.

 

The created XMLHttpRequest object has different ready states as it goes through the request. The readyState property of the object holds values corresponding to different states. They are given as follows.

  • 0 – Request is not initialized
  • 1 – Request is prepared
  • 2 – Request is sent
  • 3 – Request is processed
  • 4 – Request is complete, and the response is ready.

The onreadystatechange property of the XMLHttpRequest is set to a function. That function is going to get fired whenever the readyState property changes. Therefore, it will get called five times. But usually, we want to execute a particular script whenever the request is complete, and the response is ready, i.e., readyState = 4. We also want to make sure, before running the particular script, that the status of our request is OK. The status property of XMLHttpRequest gives us that. Some of the status response codes and their meanings are given below.

  • 200 – OK, meaning that the request is successful.
  • 202 – Accepted, meaning the request is processing.
  • 404 – Not Found, meaning the server couldn’t find what was requested.

A GET Example

Having known the basic idea, let’s go ahead and write a code that uses AJAX to retrieve students’ information from the file data.json. It is a local file stored in the same directory.

<!DOCTYPE html>
<html>
  <head>
    <title>AJAX</title>
  </head>

  <body>
    <script type="text/javascript">
      window.onload = function () {
        var http = new XMLHttpRequest();

        http.onreadystatechange = function () {
          if (http.readyState == 4 && http.status == 200) {
            console.log(JSON.parse(http.response));
          }
        };

        http.open("GET", "data.json", true);
        http.send();
      };
    </script>
  </body>
</html>

data.json file

{
  "students": [
    {
      "name": "stevin",
      "age": 9,
      "marks": 90
    },
    {
      "name": "kevin",
      "age": 10,
      "marks": 70
    },
    {
      "name": "karen",
      "age": 9,
      "marks": 94
    },
    {
      "name": "sydney",
      "age": 10,
      "marks": 80
    },
    {
      "name": "jake",
      "age": 12,
      "marks": 75
    }
  ]
}

Output

output

Let’s see what is happening in the code. We define an anonymous function that runs when the window loads. Inside that function, we create a new XMLHttpRequest, prepare the request, and send it. Note that we have used the GET method as we only want to retrieve the content, and don’t want to send any sensitive data. We know that http.onreadystatechange defines a function and whenever http.readyStatus changes, it gets called. We only want to access the data when we know that the request is OK, and the response is ready. For this purpose, we include a check that gets the response (using the http.response property) only when the http.readyState is equal to 4, and http.status is equal to 200. Since our data is in JSON format, so we have to parse it using JSON.parse() and display it to the console. The data.json file contains an object “students” equal to an array of five objects (five different students).

A POST Example

Let’s now see an example, where we send data to a server, i.e., submit.php file. Since we are sending data, we will be using the POST method. For that, we need to set the request header using http.setRequestHeader() method. It has two parameters, the name and value of the header. The submit.php file sends the JSON object as a response, which contains the status code and the message. Let’s see.

<!DOCTYPE html>
<html>
  <head>
    <title>AJAX</title>
  </head>

  <body>
    <script type="text/javascript">
      window.onload = function () {
        var http = new XMLHttpRequest();

        http.onreadystatechange = function () {
          if (http.readyState == 4 && http.status == 200) {
            console.log(http.response);
          }
        };

        http.open("POST", "http://localhost/submit.php", true);
        http.setRequestHeader(
          "Content-type",
          "application/x-www-form-urlencoded"
        );
        http.send("name=peter&age=9&marks=77");
      };
    </script>
  </body>
</html>

Output

output

Let’s look more at the properties and methods of the server response.

The responseText property of the XMLHttpRequest returns the server response as a JavaScript string. Let’s see.

<!DOCTYPE html>
<html>
  <head>
    <title>AJAX</title>
  </head>

  <body>
    <script type="text/javascript">
      window.onload = function () {
        var http = new XMLHttpRequest();

        http.onreadystatechange = function () {
          if (http.readyState == 4 && http.status == 200) {
            console.log(http.responseText);
          }
        };

        http.open("GET", "data.json", true);
        http.send();
      };
    </script>
  </body>
</html>

Output

output

While the responseText property returns the response as a JavaScript string, the responseXML property returns the response as XML data.

The getResponseHeader(headername) method returns the value of the given header. getAllResponseHeaders() returns all the headers and their values. Let’s see.

<!DOCTYPE html>
<html>
  <head>
    <title>AJAX</title>
  </head>

  <body>
    <script type="text/javascript">
      window.onload = function () {
        var http = new XMLHttpRequest();

        http.onreadystatechange = function () {
          if (http.readyState == 4 && http.status == 200) {
            console.log(JSON.parse(this.responseText));
            console.log(http.getResponseHeader("content-type"));
            console.log(http.getAllResponseHeaders());
          }
        };

        http.open("GET", "data.json", true);
        http.send();
      };
    </script>
  </body>
</html>

Output

output


Liked the post?
A computer science student having interest in web development. Well versed in Object Oriented Concepts, and its implementation in various projects. Strong grasp of various data structures and algorithms. Excellent problem solving skills.
Editor's Picks
0 COMMENT

Please login to view or add comment(s).