In this article, we take a look at three different ways that web developers can go about using Ajax in their applications, and give some sample code.
Join the DZone community and get the full member experience.Join For Free
First, What Is Ajax?
Essentially, 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.
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.
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.
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.
Published at DZone with permission of Angela Stringfellow , DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.