Languages
[Edit]
EN

JavaScript - how to return ajax response from asynchronous call?

8 points
Created by:
AnnLen
1771

1. Overview

Making request with AJAX it is necessary to make async operation - sync AJAX request technic is not recommended in main thread for many web browsers and marked as deprecated. Async operation requires callback methods or async/await keywords usage. The callback method is executed in event loop - it means 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 JavaScript program response. In this article ways to get ressponse is presented.

1.1 Common source code example

Each bellow AJAX example (from 2nd to 4th) has been executed with bellow 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.htm 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.htm 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.htm 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.htm 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.htm 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.htm¬†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.htm 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.htm 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.htm 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.htm 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.htm 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.htm¬†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.htm 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.htm 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.htm 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.htm¬†and¬†backend.php¬†files should be placed on php server both.

Result:

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

 

Hey ūüĎč
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.