Languages
[Edit]
EN

JavaScript - return ajax response from asynchronous call

11 points
Created by:
Lilly-Grace-Greig
571

In this article, we would like to show you how to return an ajax response from an asynchronous call in JavaScript​​​​​.

1. Overview

For making a request with AJAX it is necessary to make an async operation - the sync AJAX request technic is not recommended in the main thread for many web browsers and is marked as deprecated. Async operation requires callback methods or async/await keywords usage. The callback method is executed in the event loop, which means the response is not available during sequential logic execution that contains AJAX request - we need to wait until request logic will be finished and return to the JavaScript program response.

1.1 Common source code example

Each below AJAX example (from 2nd to 4th) has been executed with the below Java Spring backend logic.

EchoController.java file:

package com.dirask.examples;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

@Controller
public class EchoController
{
    @RequestMapping(value = "/examples/echo", method = RequestMethod.GET)
    @ResponseBody
    public String makeGetEcho(@RequestParam("text") String text)
    {
        return text;
    }
}

2. jQuery.ajax ($.ajax) method example

2.1. Callback method example

index.html file:

// ONLINE-RUNNER:browser;

<!doctype html>
<html lang="en">
  <head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  </head>
<body>
  <pre id="response"></pre>
  <script>

    var handle = document.getElementById('response');

    function makeRequest(callback) {
      $.ajax({
          type: 'GET',
          url: '/examples/echo',
          data: {
          	text: 'This is data...'
          },
          success: function (data) {
            callback(true, data);
          },
          error: function (jqXHR) {
            callback(false, jqXHR.status);
          }
      });
    }

    makeRequest(function(result, data) {
      handle.innerText += 'Result: ' + result + '\nData:\n' + data;
    });

  </script>
</body>
</html>

Note: ajax.html and backend.php files should be placed on php server both.

Result:

jQuery.ajax method with callback example
jQuery.ajax method with callback example

2.2. Promise with then/catch method example

index.html file:

// ONLINE-RUNNER:browser;

<!doctype html>
<html lang="en">
  <head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  </head>
<body>
  <pre id="response"></pre>
  <script>

    var handle = document.getElementById('response');

    function makeRequest() {
      var promise = new Promise(function(resolve, reject) {
        $.ajax({
          type: 'GET',
          url: '/examples/echo',
          data: {
          	text: 'This is data...'
          },
          success: function (data) {
            resolve(data);
          },
          error: function (jqXHR) {
            reject(jqXHR.status);
          }
        });
      });

      return promise;
    }

    var promise = makeRequest();

    promise.then(function(data) {
      handle.innerText += 'Result: true\nData:\n' + data;
    });

    promise.catch(function(status) {
      handle.innerText += 'Error: ' + status;
    });

  </script>
</body>
</html>

Note: ajax.html and backend.php files should be placed on php server both.

Result:

jQuery.ajax Promise with then/catch method example
jQuery.ajax Promise with then/catch method example

2.3. Promise with async/await keywords example

index.html file:

// ONLINE-RUNNER:browser;

<!doctype html>
<html lang="en">
  <head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  </head>
<body>
  <pre id="response"></pre>
  <script>

    var handle = document.getElementById('response');

    function makeRequest() {
      var promise = new Promise(function(resolve, reject) {
        $.ajax({
          type: 'GET',
          url: '/examples/echo',
          data: {
          	text: 'This is data...'
          },
          success: function (data) {
            resolve(data);
          },
          error: function (jqXHR) {
            reject(jqXHR.status);
          }
        });
      });

      return promise;
    }

    (async function() {
      try {
        var data = await makeRequest();

        handle.innerText += 'Result: true\nData:\n' + data;
      } catch(status) {
        handle.innerText += 'Error: ' + status;
      }
    })();

  </script>
</body>
</html>

Notes:

  • await operations can be executed only in async methods - this way makes an impression the operation looks like assigning returned value in sync programming.
  • ajax.html and backend.php files should be placed on php server both.

Result:

jQuery.ajax Promise with async/await keywords example
jQuery.ajax Promise with async/await keywords example

3. XMLHttpRequest class example

3.1. Callback method example

index.html file:

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<body>
  <pre id="response"></pre>
  <script>

    var handle = document.getElementById('response');

    function makeRequest(callback) {
      var xhr = new XMLHttpRequest();

      xhr.onreadystatechange = function () {
          if (xhr.readyState == XMLHttpRequest.DONE) {
              if (xhr.status == 200) {
                callback(true, xhr.responseText);
              } else {
                callback(false, xhr.status);
              }
          }
      };
      
      var text = encodeURIComponent('This is data...');

      xhr.open('GET', '/examples/echo?text=' + text, true);
      xhr.send(null);
    }

    makeRequest(function(result, data) {
      handle.innerText += 'Result: ' + result + '\nData:\n' + data;
    });

  </script>
</body>
</html>

Note: ajax.html and backend.php files should be placed on php server both.

Result:

XMLHttpRequest with callback method example
XMLHttpRequest with callback method example

3.2. Promise with then/catch method example

index.html file:

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<body>
  <pre id="response"></pre>
  <script>

    var handle = document.getElementById('response');

    function makeRequest() {
      var promise = new Promise(function(resolve, reject) {
        var xhr = new XMLHttpRequest();

        xhr.onreadystatechange = function () {
            if (xhr.readyState == XMLHttpRequest.DONE) {
                if (xhr.status == 200) {
                  resolve(xhr.responseText);
                } else {
                  reject(xhr.status);
                }
            }
        };

        var text = encodeURIComponent('This is data...');

      	xhr.open('GET', '/examples/echo?text=' + text, true);
        xhr.send(null);
      });

      return promise;
    }

    var promise = makeRequest();

    promise.then(function(data) {
      handle.innerText += 'Result: true\nData:\n' + data;
    });

    promise.catch(function(status) {
      handle.innerText += 'Error: ' + status;
    });

  </script>
</body>
</html>

Note: ajax.html and backend.php files should be placed on php server both.

Result:

XMLHttpRequest Promise with then/catch method example
XMLHttpRequest Promise with then/catch method example

3.3. Promise with async/await keywords example

index.html file:

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<body>
  <pre id="response"></pre>
  <script>

    var handle = document.getElementById('response');

    function makeRequest() {
      var promise = new Promise(function(resolve, reject) {
        var xhr = new XMLHttpRequest();

        xhr.onreadystatechange = function () {
            if (xhr.readyState == XMLHttpRequest.DONE) {
                if (xhr.status == 200) {
                  resolve(xhr.responseText);
                } else {
                  reject(xhr.status);
                }
            }
        };

        var text = encodeURIComponent('This is data...');

      	xhr.open('GET', '/examples/echo?text=' + text, true);
        xhr.send(null);
      });

      return promise;
    }

    (async function() {
      try {
        var data = await makeRequest();

        handle.innerText += 'Result: true\nData:\n' + data;
      } catch(status) {
        handle.innerText += 'Error: ' + status;
      }
    })();

  </script>
</body>
</html>

Notes:

  • await operations can be executed only in async methods - this way makes an impression the operation looks like assigning returned value in sync programming.
  • ajax.html and backend.php files should be placed on php server both.

Result:

XMLHttpRequest Promise with async/await keywords example
XMLHttpRequest Promise with async/await keywords example

4. fetch method example

4.1. then/catch method example

index.html file:

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<body>
  <pre id="response"></pre>
  <script>

    var handle = document.getElementById('response');

    var text = encodeURIComponent('This is data...');
    var promise = fetch('/examples/echo?text=' + text);

    promise.then(function(data) {
      var text = data.text();
      
      text.then(function(response) {
      	handle.innerText += 'Result: true\nData:\n' + response;
      });
    });

    promise.catch(function(error) {
      handle.innerText += 'Error: ' + error.message;
    });

  </script>
</body>
</html>

Note: ajax.html and backend.php files should be placed on php server both.

Result:

fetch with then/catch method example
fetch with then/catch method example

4.2. async/await keywords example

index.html file:

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<body>
  <pre id="response"></pre>
  <script>

    var handle = document.getElementById('response');

    (async function() {
      try {
        var text = encodeURIComponent('This is data...');
    	var promise = await fetch('/examples/echo?text=' + text);
        var response = await promise.text();

        handle.innerText += 'Result: true\nData:\n' + response;
      } catch(error) {
        handle.innerText += 'Error: ' + error.message;
      }
    })();

  </script>
</body>
</html>

Notes:

  • await operations can be executed only in async methods - this way makes an impression the operation looks like assigning returned value in sync programming.
  • ajax.html and backend.php files should be placed on php server both.

Result:

fetch async/await keywords example
fetch async/await keywords example

Alternative titles

  1. JavaScript - how to return ajax response from asynchronous call?
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join