JavaScript - return ajax response from asynchronous call
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.htmlandbackend.phpfiles should be placed on php server both.
Result:
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.htmlandbackend.phpfiles should be placed on php server both.
Result:
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:
awaitoperations can be executed only inasyncmethods - this way makes an impression the operation looks like assigning returned value in sync programming.ajax.htmlandbackend.phpfiles should be placed on php server both.
Result:
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.htmlandbackend.phpfiles should be placed on php server both.
Result:
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.htmlandbackend.phpfiles should be placed on php server both.
Result:
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:
awaitoperations can be executed only inasyncmethods - this way makes an impression the operation looks like assigning returned value in sync programming.ajax.htmlandbackend.phpfiles should be placed on php server both.
Result:
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.htmlandbackend.phpfiles should be placed on php server both.
Result:
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:
awaitoperations can be executed only inasyncmethods - this way makes an impression the operation looks like assigning returned value in sync programming.ajax.htmlandbackend.phpfiles should be placed on php server both.
Result: