ajax asynchronous call

How to get the return a value from a AJAX asynchronous call with jQuery and AngularJS $http

Web applications often make use of dynamic views. These require some JavaScript skills usually and I think that one of the most common use of JavaScript for web apps with dynamic views is the AJAX asynchronous call. With AJAX one is able to load data within a page without having to reload the whole page making the dynamic part a smooth experience for the end user.

jquery ajax

AJAX asynchronous calls with jQuery

jQuery is one of the most popular JavaScript library to date. To make AJAX calls with jQuery one would have to write something like:

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

Nothing complicated so far. The url parameter indicates the URL where to send the request and success indicates what to do when receiving the response. What is important to note here is that running $.ajax will not stop to wait for the answer, that’s where the asynchronous term comes in. So code execution will continue immediately with any calls after the AJAX call.

The opposite of these are synchronous calls which wait for the return of the function and then move on to the next part of the code.

angularjs http

AJAX asynchronous calls with AngularJS $http

It really doesn’t matter what library you use, the philosophy of AJAX calls is the same. If you are using AngularJS you would write something like this:

$http.get('/someUrl', config).then(successCallback, errorCallback);

The difference between this and the jQuery version is that with $http object you have to use the HTTP method you need, in this case get (corresponding to the GET HTTP method) which in jQuery’s ajax case is the default method.

Also, the method then takes 2 parameters which have to be functions. First one is a function to handle the successful response from the GET request and the second one is a function that will handle the error in case there is any error coming back from the server.

Getting and using the response from an AJAX asynchronous call

No matter what library you use for making AJAX asynchronous calls the result will be passed to a function when the server responds. This function is known as a callback function. In case of jQuery we saw that this function is passed in as the success parameter, and for AngularJS $http it’s the first parameter of the then function.

In both cases the callback function receives the response from the server as the first parameter. I’ve had a lot of beginner and intermediate JavaScript programmers having difficulties with transforming code with synchronous code to one AJAX asynchronous calls.

Let’s take an overly simplified example with synchronous calls:

var users = ["John Doe", "Jane Doe", "Jimmy Doe", "Donnovan Doe"];

function displayList(items){
 for (var i=0;i<items.length;i++){
 document.write(items[i] +"<br/>");
 }
}

alert("Starting to display users");
displayList(users);
alert("Done displaying users");

Very often if you need to write code that relies on external data, you will first start with some static data before hooking up the code to dynamic data.

In the example above we have a list of users – the Doe family – which will be displayed one by one by the displayList function.

The order in which things will be executed is:

  1. Showing the message “Starting to display users”
  2. Listing in the document the 4 users in the users array
  3. Showing the message “Done displaying users”

Nothing too complicated. But what happens if the list of users comes from the server from a database for example. Let’s see how we have to transform the code to use an AJAX asynchronous call. We will assume that the server component that gets the users from the database is users.php and that the format that the server responds in is JSON.

function displayList(items){
 for (var i=0;i<items.length;i++){
 document.write(items[i] +"<br/>");
 }
}

alert("Starting to display users");
$.ajax({
 url:'users.php',
 success:function(response){
   var users = response;
   displayList(users); 
   alert("Done displaying users");
 }
})

In order to keep the same order of execution as above we had to move the second alert inside the success function. So, the AJAX call is made to the users.php component and only after the server responds with the list of users the users are displayed.

When using AngularJS the code would look like this:

function displayList(items){
 for (var i=0;i<items.length;i++){
  document.write(items[i] +"<br/>");
 }
}

alert("Starting to display users");
$http.get('users.php', {}).then(
 function(response){
  var users = response;
  displayList(users); 
  alert("Done displaying users");
 },
 function (){
  //handle server error
 }
);

The result is exactly the same as in the AJAX call with jQuery above.

Hope you found this tutorial helpful.

 

John Negoita

View posts by John Negoita
I'm a Java programmer, been into programming since 1999 and having tons of fun with it.
[jetpack-related-posts]

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top