How to Return Ajax Response From Asynchronous JavaScript Call: Methods and Code Examples
When JavaScript is used in conjunction with XML or REST APIs, you can create some useful behaviors with a set of web-development techniques collectively known as Ajax. Let's take a look at a specific Ajax functionality: returning an Ajax response from an asynchronous JavaScript call.
First, What Is Ajax?
Asynchronous JavaScript and XML, or Ajax, isn't a new technology in itself, and it's not a programming language. The term was coined back in 2005 by Jesse James Garrett. As the Mozilla Developer Network explains, Ajax "describes a 'new' approach to using a number of existing technologies together, including HTML or XHTML, Cascading Style Sheets, JavaScript, The Document Object Model, XML, XSLT, and most importantly the XMLHttpRequest object."
Screenshot via W3Schools.comEssentially, it serves as a bridge between database and server without requiring the user to refresh the page. It is a better way to create faster, more responsive, and better web-based applications using HTML, Java Script, XML or JSON, and CSS. Using Ajax, a page is able to request things from the server, process the results, and then update the page - all of which happens without the user sensing what's going on or having to take additional actions.
Where Is Ajax Used?
Ajax is commonly used in Web applications where small tidbits of information are retrieved or saved without needing to reload an entire page. Take, for example, saving a comment on a message board. Ajax is also used on auto-complete boxes and text hints, where you can type the first letters and the system would try to guess what you are typing and suggest words or phrases for you.
Note that while the "X" in Ajax represents XML, JSON is more commonly used today as it's both lightweight and a part of JavaScript. However, both JSON and XML can be used to package information in the Ajax model. In addition to JSON and XML, data can also be transported as plain text.
Challenges of Asynchronous Methods Like Ajax
Asynchronous methods cannot easily return its value, unlike traditional methods. This is because the results are computed asynchronously or in such a way that one operation begins only when the previous operation has been completed, so the method might have returned before the result is calculated.
If you use multi-threads, you can easily get around this by synchronously waiting for the asynchronous operation to terminate. But that would mean you wouldn't be able to take full advantage of the benefits of asynchronicity.
Asynchronous methods allow you to free up the thread even when the operation is still running. In JavaScript and other single thread languages, there is also no way to go around this because a waiting method means that a result would never be arrived at.
How to Use Asynchronous Methods in Ajax
Ajax is a very well known method for loading the content of a Web page without manually refreshing it. But the letter "A" in Ajax means asynchronous, meaning that you need to have a callback function that will return the results.
You can always use a synchronous call, but that will freeze your page and maybe turn off some of your users. You can think of synchronous methods like making a telephone call and being put on hold while the call is being redirected to the person you want to talk to. While on hold, there is nothing that you can do but just wait until the other party speaks.
This means that if you have any other code next to var item = findItem(); these would not execute unless the function gives a result.
Now for asynchronous methods, let's go back to the phone call example. For instance, you call somebody you want to talk to, but the person is not available, so you leave a message to have him or her call you back. This way, you no longer have to wait on the phone listening to the hold music, you can do other things until the person returns your call. Ajax requests do just that.
With this, all codes following this one will execute immediately; you will not have to wait until the function returns. This way, your user would not have to wait for findItem() to return a result. Of course, because you still need an answer, you would have to include a callback. A callback is a function that would give you the result or response you wanted, and it is typically called after all statements after the findItem() has been executed.
Solution 1: Making Synchronous AJAX Calls
The first solution has already been mentioned above. You can write asynchronous AJAX calls so that it waits for the response before moving on to the next statements. If you are using jQuery, you can easily do this by setting the async option to false.
However, if you are not using jQuery, like when you use $.getJSON, $.get, and others, you will need to revise it to $.ajax and then use async: .open instead of async: false if you are using an XMLHTTPREQUEST object.
Moreover, if you are using JSONP, you will not be able to create a synchronous JSONP call because JSONP is, by default, asynchronous.
While this might help you solve the problem of getting a return response to your Ajax call, there is no doubt that you will run into problems using this solution. For one, if there are any long processes in a JavaScript code, it will lock the user interface and make it unresponsive.
JavaScript execution times are also limited, and when it reaches its limit, the browser will prompt the user to ask whether he or she wants to continue executing the code or not. Both the browser hanging and a pop-up window asking the user to continue, translate to a bad user experience. What's more, the user will have no way of telling if the code is working all right or if it has crashed the browser. This is especially true with users who have a slow Internet connection.
Solution 2: Make Functions Accept Callbacks
A much better solution is to make your functions accept callbacks and rewrite your code around these.
Here's an example from <node-tricks]. If you have:
You should write it as:
This will make the foo accept a callback, which it will then use as success callback. Then you can set up a function as an argument to foo, like this:
Then define foo as:
When this code executes, callback will go back to the original function that we have set up to foo. $.ajax will call the callback function and give the response.
Solution 3: Deferred Objects
There are times when directly passing a callback is not ideal for your application. The good news is that for these situations, you can rely on deferred objects or those that represent a value that may be available at a certain point in the future. Deferred objects make use of a then() method when you're passing a callback so that it will execute when the value becomes available. In short, using deferred objects, you can chain your Ajax calls without nesting any part of your code.