Explain the role of callback function in AJAX


AJAX (Asynchronous JavaScript and XML) is not a programming language but a technique for creating more interactive web applications. Unlike conventional web applications, which direct us to a new page when interacting with the server, AJAX loads data onto the screen without letting the user know that the request was even made.

Advantages

  • Displays content dynamically without reloading the HTML page.

  • Faster interaction with the users.

  • Updates the data within the page without redirecting the user.

  • Users were allowed to use the website while communication with the server went in the background.

What is meant by Callback Function?

The callback function is a function that is passed as an argument to another function and invoked internally to perform required tasks.

In AJAX, the callback function is called once the request to the server is completed. Response and the status of AJAX calls are passed into this function internally. The callback function performs the required action using the response obtained. Thus, it is very important in AJAX because it is all about dealing with the requested data.

There are two ways of Using the Callback Function

  • Anonymous callback function

  • Named callback function

Anonymous Callback Function

Step 1: Creating an XMLHttpRequest

XMLHttpRequest is a built-in object of javascript through which data is transported to and from the server. Thus the requests are made to the server, and responses are received.

Step 2: Use the open() method

A method of XMLHttpRequest is used to create a request to the server.

Syntax

open(method, url, async, user, password)

Here, async, user, and password attributes are optional.

  • method – GET, POST, PUT, DELETE for HTTP URLs.

  • url – The Uniform Resource Locator to which the request needs to be sent

  • async – Indicates whether the request is to be sent asynchronously or not. The default value is “true”.

  • async = “true” handles the request asynchronously, i.e., it does not freeze the user until the server receives a response.

    async = “false” indicated handling the request synchronously.

  • user, password – If authentication is involved, mentioning username or both username and password is necessary. The default value is “null”.

Step 3: Use send() method

This is also a method of XMLHttpRequest used to send the request. If the request is asynchronous (async attribute of open() is true), this is returned once the request is successfully sent.

If synchronous, the method will not return until the response is received from the server; the user should remain idle.

Step 4: Use onreadystatechange property

To manage the response, we use the property of XMLHttpRequest called – onreadystatechange.

Step 5: Call the callback function

Now call a callback function by attaching with onreadystatechange as the anonymous function. Now perform the required action on the received data by writing all the code inside this function.

Note

Onreadystatechange property defines the function to be executed when the readystate (status of XMLHttpRequest) changes.

Ready State values

0 − request not initialized

1 − server connection established

2 − request received

3 − processing request

4 − request is finished, and the response is ready

HTTP status values

200 − OK

403 − Forbidden

404 − not found, etc.

Example 1

Let’s look into a simple example where we display some content on the HTML page based on button clicks. The request is sent to the server using AJAX. When the readyState becomes 4, we display the click count of the button.

callbackdemo.html

<html>
<body>
   <h2> Anonymous callback function </h2>
   <button id = "btn" onclick = "callback_fn()"> Click Here </button>
   <div id = "info" style = "width: 200px; border: 1px solid black; padding: 1%"> </div>
   <script>
      var count = 0;
      var string;
      let info = document.getElementById('info')
      function callback_fn() {
         info.innerHTML = 'AJAX Call <br /><br />'
         
         //AJAX Call
         let http = new XMLHttpRequest();
         http.onreadystatechange = function () {
            if(this.readyState == 4){
               count++;
               string = count.toString();
               info.innerHTML += 'Button clicked '+string+' time <br/>';
            }
         }
         info.innerHTML += 'Started here! <br /><br />'
         http.open('GET', 'https://jsonplaceholder.typicode.com/posts/', true)
         http.onload = function () {
            info.innerHTML += '<br />AJAX Call Completed!'
         }
         http.send()
      }
   </script>
</body>
</html>

Note − We can also add event listeners so the requests would be sent by clicking a button or other elements of HTML.

Named Callback Function

  • Step 1 − Define a callback function with a name

  • Initially, define a callback function with a proper name, and include the code to deal with the response received from the server.

  • Step 2 − Create an XMLHttpRequest

  • Step 3 − Use the open() method

  • Step 4 − Use the send() method

  • Step 5 − Use the onreadystatechange property of XMLHttpRequest

  • Step 6 − Call the callback function

    Call the named callback function by attaching it with the onreadystatechange property.

Example 2

This is a simple example of displaying data from a JSON file on the HTML page using the named callback function. The request is sent using AJAX to get data from the file.

When the button is clicked on an html page, click_fn( ) is called, which calls the callback function after sending the request. Here, the name of the callback function is “named_callback”.

callbackdemo.html

<html>
<head>
   <script type = "text/javascript" src = "script.js”> </script>
</head>
<body>
   <h2> Named Callback Function in AJAX </h2>
   <button id = "btn" onclick = "click_fn()"> Click Here </button> <br> <br> <br>
   <h3 id = "info"></h3>
</body>
</html>

script.js

var btn = document.getElementById("btn");
function named_callback() {
   if (this.readyState == 4 && this.status == 200) {
      var txt = "";
      var data = JSON.parse(this.responseText);
      for(i=0;i<data.length;i++){
         var x=i+1;
         txt += "<u>"+"Details of person "+x.toString()+"</u>"+"<br>";
         var age=(data[i].Age);
         txt += "<p>" +data[i].Name + " age is " + age + ", loves to play "+data[i].Sport+".</p>" ;
      }
      document.getElementById("info").innerHTML = txt;
   }
}
function click_fn() {
   var http = new XMLHttpRequest();
   http.open("GET", "details.json");
   http.send();
   http.onreadystatechange = named_callback;
}

details.json

[
   {"Name":"Sreya", "Age":"21", "Sport":"Badminton"},
   {"Name":"Suresh", "Age":"23", "Sport":"Cricket"}
]

Updated on: 17-Mar-2023

848 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements