Interview Questions

How do I get and use the server response from an AJAX request?

jQuery Interview Questions and Answers


(Continued from previous question...)

How do I get and use the server response from an AJAX request?

The 'A' in AJAX stands for asynchronous. When invoking functions that have asynchronous behavior you must provide a callback function to capture the desired result. This is especially important with AJAX in the browser because when a remote request is made, it is indeterminate when (or even if) the response will be received.

The following snippet shows an example of making an AJAX call and alerting the response (or error):

$.ajax({
url: 'myPage.php',
success: function(response) {
alert(response);
},

error: function(xhr) { alert('Error! Status = ' + xhr.status);
}
});


But how can the response be used in context of a function? Consider this flawed example where we try to update some status information on the page:

function updateStatus() {
var status;
$.ajax({
url: 'getStatus.php',
success: function(response) {
status = response;
}
});
// update status element? this will not work as expected
$('#status').html(status);
}


The code above does not work as desired due to the nature of asynchronous programming. The provided success handler is not invoked immediately, but rather at some time in the future when the response is received from the server. So when we use the 'status' variable immediately after the $.ajax call, its value is still undefined. The next snippet shows how we can rewrite this function to behave as desired:

function updateStatus() {
$.ajax({
url: 'getStatus.php',
success: function(response) {
// update status element
$('#status').html(response);
}
});
}


But how can I return the server response from an AJAX call? Here again we show a flawed attempt. In this example we attempt to alert the http status code for the url of 'getStatus.php':

//...
alert(getUrlStatus('getStatus.php'));
//...
function getUrlStatus(url) {
$.ajax({
url: url,
complete: function(xhr) {
return xhr.status;
}
});
}


The code above will not work because you cannot 'return' data from a function that is called asynchronously. Instead, it must be rewritten to use a callback:

//...
getUrlStatus('getStatus.php', function(status) {
alert(status);
});


// ...
function getUrlStatus(url, callback) {
$.ajax({
url: url,
complete: function(xhr) {
callback(xhr.status);
}
});
}

(Continued on next question...)

Other Interview Questions