How to return response from asynchronous call

How To Return Response From Asynchronous Call

In this tutorial, you’ll learn how to return response from asynchronous call. Before diving deep inside let’s try to understand what is an asynchronous call.

JavaScript is single threaded and all code is executed in a sequence, synchronously. Any I/O operations in your code will block the flow of code until it’s complete, which in turn makes the web browser unresponsive.

You can counter this blocking I/O operation by using the asychronous non-blocking I/O model. In asynchronous non-blocking I/O model all the I/O operations are handled asynchronously without blocking the code execution.

Suppose while loading a web page you need to fetch some data from a REST API endpoint. One approach would be to wait for the data to be fetched from the API and block the code execution. But that will make the web browser unresponsive and give the user a not so friendly user experience. Another approach will be to make use of AJAX (Asynchronous JavaScript And XML) to pull in the data asynchronously from external APIs without blocking the execution of code. Once the data has been loaded it, a callback is executed to process the response and render it.

In this tutorial, you’ll see different ways to make asynchronous calls and return response from it.

Return Response From Asynchronous Call Using XMLHttpRequest

From Wikipedia,

XMLHttpRequest (XHR) is an API in the form of an object whose methods transfer data between a web browser and a web server. The object is provided by the browser’s JavaScript environment. Particularly, retrieval of data from XHR for the purpose of continually modifying a loaded web page is the underlying concept of Ajax design.

Let’s start by creating a folder called asyncResponse. Inside asyncResponse create a file called index.html. Create a JavaScript file called index.js and include a reference to it from index.html.

<!DOCTYPE html>
<html>
<head>
    <title> How To Return Response From Asynchronous Call </title>
    <script type="text/javascript" src="index.js"></script>
</head>
<body>
    <button id="btnAjax"> Make XMLHTTPRequest </button>
    <div id="divResult">
        
    </div>
</body>
</html>

Create a JavaScript file called index.js. Inside index.js on DOMContentLoaded event add a click event listener to the button btnAjax.

document.addEventListener("DOMContentLoaded", function(event) {
    document.getElementById('btnAjax').addEventListener('click', function() {
        
    })
});

On the button click event you’ll be creating an XMLHttpRequest object to make the AJAX calls. Here is how you make an AJAX request to an API endpoint using XMLHttpRequest.

/* index.js file */

let httpRequest;
/*
** DOMContentLoaded works when DOM is loaded
*/
document.addEventListener("DOMContentLoaded", function(event) {
    document.getElementById('btnAjax').addEventListener('click', function() {
        httpRequest = new XMLHttpRequest();
        /* added an on ready state change event to handle XMLHttpRequest state change */
        httpRequest.onreadystatechange = parseResponse;
        httpRequest.open('GET', 'http://jsonplaceholder.typicode.com/users');
        httpRequest.send();
    })
});

/*
** XMLHttpRequest state change callback handler
*/
function parseResponse() {
    if (httpRequest.readyState === XMLHttpRequest.DONE) {
      if (httpRequest.status === 200) {
        console.log(httpRequest.responseText);
        document.getElementById('divResult').innerHTML = httpRequest.responseText
      } else {
        console.log('something broke ....')
      }
    }
}

As seen in the above code XMLHttpRequest has been used to make the API call. When the state of the XMLHttpRequest changes a callback function is executed. Inside the callback function you can confirm if the XMLHttpRequest is completed by checking the readyState of the httpRequest object. XMLHttpRequest is completed when the readyState is DONE.

Once the ready state is DONE you can get the API response from httpRequest.responseText.

Return Response From Asynchronous Call Using jQuery AJAX

Making an API call using XMLHttpRequest using vanilla JavaScipt has a lot of code. jQuery made it simpler to make an AJAX call by writing a wrapper over the XMLHttpRequest object. jQuery provides a method called $.ajax to make asynchronous calls using jQuery library without bothering about XMLHttpRequest.

Let’s try it out by including jQuery library in our index.html page.

<!DOCTYPE html>
<html>
<head>
    <title> How To Return Response From Asynchronous Call </title>
    <script type="text/javascript" src="index.js"></script>
    <script type="text/javascript" src="jquery-3.3.1.js"></script>
    <script type="text/javascript" src="jQueryAjax.js"></script>
</head>
<body>
    <button id="btnAjax"> Make XMLHTTPRequest </button>
    <button id="btnjQueryAjax"> Make jQuery AJAX </button>
    <div id="divResult">
        
    </div>
</body>
</html>

Create a file called jQueryAjax.js to write the jQuery code for making AJAX calls and rendering the response.

Inside the jQueryAjax.js file attach the click event on btnjQueryAjax button’s click. Here is how the jQueryAjax.js file looks :

$(function(){
    $('#btnjQueryAjax').click(function(){
        $.ajax({
            url : 'http://jsonplaceholder.typicode.com/users',
            type: 'GET',
            success: function(response) {
                $('#divResult').html(JSON.stringify(response))
            },
            error : function(error) {
                console.log('error is ', error)
            }
        })
    })
})

The response from the asynchronous call can be parsed in the success callback of the $.ajax method as seen in the above code.

Summarizing

In this tutorial, you learnt what is an asynchronous call and how to return response from asynchronous call using XMLHttpRequest and jQuery AJAX. Source code from this tutorial is available on GitHub.