The Power of AJAX and How to Use it

Since its conception in 2005, AJAX (Asynchronous Javascript and XML) has changed the web world as we know it today. It’s helped websites evolve into RIAs (rich internet applications) by allowing webpages to make direct requests to a web server without reloading the page. This capability is vital in replicating the rich user experiences achieved in client applications. The purpose of this post is to help newcomers understand the different ways that AJAX can be used to create RIAs.

How AJAX Works

An AJAX call is made from Javascript by calling a URL with specific parameters. This URL typically points to a servlet on a web server which takes the parameters that you’ve provided and queries your database. If a response is required, the serlvet puts together either a response message or an http friendly data structure like JSON, XML, or CSV, and sends it back to the client.

An example implementation

Let’s say that you have a login form for your web application. To ensure that the provided login name and password is a match without using AJAX, your web application would have to load a whole new webpage that shows an account screen if the login was successful, or show an error screen if the login failed. This is the “old way” of logging users into their accounts.

A more savvy approach to this problem would be to check if the login and password is correct using AJAX. Here’s how it would work. Once the user has typed in a login name and password, and pressed “Enter”, you could have a Javascript function that invokes an AJAX call and sends two parameters, the login name and password. The web server takes those two inputs, and queries your user database to see if there is a match. If there is, then the web server can return a success flag like “SUCCESS”. If there is an error like “This user does not exist” or “Password does not match” then the web server could return one of these error messages. You would then have a Javascript function that accepts the AJAX response. If the response is “SUCCESS”, it uses window.location to send the user to their account screen. If the response contains one of the error messages, it can immediately show the error on the screen without ever reloading the page.

Good luck!

Tagged in:,
About