You are on page 1of 9

Page 1 of 9

10/20/10 - Do you want to implement ajax features but you don't know how?

Ajax is always more and more diffused and common in various websites, at times even when it's not necessary, but after all this happens somehow with everything. If you are attracted by this technology but you don't know where to start from, this article is for you. In two extremely simple examples you will learn the basics and you will see how thanks to the use of modern frameworks it is not as difficult as it might look. You don't believe me?

What is a asynchronous call?


If we don't use Ajax, every data exchange between the server and the client requires a traditional request which entails the refreshing or the loading of a new page. When we fill a form and click on "send", for example, the elaboration page is requested to the server which will deal with intercepting the data we inserted into the form, elaborating them, and finally show a result. This page is loaded as a new document which is completely going to substitute the previous page (the one of the form) in our browser. Thanks to ajax instead, the server and the client can communicate "in background" at time intervals or at the occurrence of a certain event. We can thus for example foresee that by clicking on the "send" button of a form (thus at the occurrence of the submit event), a request is sent that is going to be elaborated by the server which is going to send the result to the browser which in turn is going to show it, everything without the page having to reload.

Page 2 of 9

This is exactly what we are going to do together in a little bit. We are going to use jQuery, the powerful javascript library which has already been the subject of several articles and thanks to which the creation of a asynchronous call will result extremely simplified. If you don't have jQuery yet (wrong), download it from the official website.

Preparation of the form


We create the page ajax.html and insert a simple form which requires "name" and "last name". Array<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">Array<html>Array<head>A rray</head>Array<body>ArrayArray<form id="input_form" action="?">Array Insert name:<br />Array <input type="text" name="name" id="name"/><br />Array Insert last name:<br>Array <input type="text" name="lastname" id="lastname"/><br/ ><br/ >Array <input type="submit" value="send">Array</form>ArrayArray<div id="result"></div>ArrayArray</body>Array</html>Array

In this HTML markup we have added the "result" element which represents the point in which the results of the elaboration from the server are going to be inserted.

Preparation of the elaboration page on the server


Let's create now the page result.php which will provide for the reception and elaboration of data passed from the form: Array<?phpArrayecho "You have inserted the following data: Name-><strong>$_POST[name]</strong> and Last name-><strong>$_POST[lastname]</strong>. You have executed an asynchronous call!";Array?>Array

As you can see it's simply about printing on video the data passed from the form inside a phrase.

Page 3 of 9

Inclusion of jQuery and preparation of function


Let's turn now to the file ajax.html. We include the jQuery library and arrange for the function necessary for our scope modifying the head in this way: Array<head>Array <script type="text/javascript" src="jquery-1.4.1.js"></script> <!-- The version could be different -->Array <script type="text/javascript">Array $(document).ready(function() {Array //Here we will write the necessary codeArray });Array</script>Array</head>Array

Let's create now the necessary jQuery code which I am going to explain in detail below. Array$("#input_form").submit(function(){Array var name = $("#name").attr('value');Array var lastname = $("#lastname").attr('value');Array $.post("result.php", {name:name,lastname:lastname}, function(data){Array $("div#result").html(data);Array });Arrayreturn false;Array});Array

So, in the first line we state: Array$("#input_form").submit(function(){Array

In the element with id "input_form", at the occurrence of "submit" event, execute this function. In the second and third line: Arrayvar name = $("#name").attr('value');Arrayvar lastname = $("#lastname").attr('value');Array

we emphasize the variables name and last name withdrawing the "value" attribute from the elements with id "name" and "last name" (which are the relative fields of the form).

Page 4 of 9

At this point we proceed with the ajax call. jQuery has mainly three methods for the management of asynchronous calls, $.post, $.get, ed $.ajax. In this first example we are going to use $.post which as it's obvious will send the data to the server through the POST method. The syntax is simple: $.post("name_of_file", {name1:value1,name2:value2( passed parameters)}, function(data){ ? what we want to do with the answer sent to us by the server is that it will be contained in the "data" parameter. }); In our case, we send the request to result.php passing as parameter name the variable name (previously enhanced with the content of the field name of form) and as last name parameter the last name variable. We insert the result in the element "result". Finally, if we use the forms, we should always bear in mind to interrupt the execution of submit with return false.

By trying out this code (see example) under the form you will display the phrase without a refresh or the loading request of a new page. The data have been sent in asynchronous way to the server which has executed the php page. The output of the page has been thus sent to the client and inserted in DOM. If I wanted to use $.ajax to do exactly the same thing, I have to rewrite the function like this: Array$.ajax({Array url: 'result.php',Array type: "POST",Array data: "name="+name+"&lastname="+lastname,Array success: function(data) {Array $("div#result").html(data);Array }Array});Array

As you can see $.ajax has a different and slightly more complex syntax. This as it

Page 5 of 9

allows us to pass a long series of parameters (and in fact more configurable than $.post and $.get); you will find the complete list of parameters in the documentation. Let's make now another example. Some time ago Nicolas wrote a very detailed article titled "You want to use Json but don't know where to start from?". Well then, if you are not familiar with the Json format, I advise you to reread this article, otherwise keep reading.

How to manage the json format in ajax calls?


In this second example, we will use the submit button of a form to make a request to the server. More specifically we will ask it to send us the timestamp, current time and date. You can see the result in this example page. Let's start from the php page (result2.php). Array<?phpArray$time = time();Array$hour = date("H:i:s");Array$day = date("j/n/Y");Arrayecho "{'timestamp':'$time','hour':'$hour','day':'$day'}";Array?>Arr ay

We take the timestamp, time and date and subsequently execute the output on video in Json format (name:value). Let's pass now to the page ajax-json.html Array<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">Array<html>Array<head>A rray <script type="text/javascript" src="jquery-1.3.2.js"></script>Array <style>Array #result{Array width: 250px;Array height: 100px;Array border: 1px solid gray;Array }Array </style>Array <script type="text/javascript">Array $(document).ready(function() {Array // here we will write the functionArray });Array </script>Array</head>Array<body>Array<form id="input_form" action="?">Array <input type="submit" value="request data">Array</form>ArrayArray<div id="result">Array The actual timestamp is: <span id="timestamp"></span><br />Array

Page 6 of 9

which corresponds to time: <span id="hour"></span><br />Array of day: <span id="day"></span>Array</div>Array</body>Array</html>Array

As you can see, the form is composed only by the button. In the element #result I have prepared the phrases which following the request to the server are going to be completed with the sent data. Let's see how. Array$("#input_form").submit(function(){Array $.ajax({Array url: 'result2.php',Array dataType: "json",Array success: function(data) {Array $("#timestamp").html(data.timestamp);Array $("#hour").html(data.hour);Array $("#day").html(data.day);Array }Array });Arrayreturn false;Array});Array

What does this code mean? In the element #input_form, at the occurrence of the submit event, execute this function: Make an ajax request to the result2.php page. Now that we have set the dataType property with the "json" value. This tells jquery that it has to expect an answer in this format, therefore the answer from the server will be inserted in the "data" object. Therefore, for example, the value we passed with the name day (?day':'$day') we will recover in data.day. In this way we can insert the three values (the interesting thing is that contrary to the previous example, in which the result was a single block, now we can manage the data individually) in the established position based on the assigned id.

Ajax and usability


We always have to pay a lot of attention when using ajax. Let's suppose that the request is very complex and/or that the server is particularly slow or congested. The process could last even several seconds. With a traditional request, down on the left of the browser we see messages:

Page 7 of 9

"Waiting for www.....", "Transferring data from www....", etc. If the request is done in ajax this doesn't happen. As a consequence, the user could have the impression that nothing is happening and maybe would push the send button a couple of times. This is an error of usability in contradiction with paragraph one (visibility and state of the system) and paragraph five (error prevention) of Nilsen's decalogue. Therefore we disable the button for the entire length of the request and make appear an image which clearly indicates that something is happening, for example this:

Let's use the last example (ajax-json.html) and modify it as follows: We insert the image next to the button Array<input type="submit" value="request data" class="button"> <img src="loading.gif" border="0" class="loading">

We render it invisible by adding this class to our style sheet: Array.loading{Array display: none;Array}Array

Now at the occurrence of the submit event we disable the button and display the image: Array$(".button").attr("disabled", "disabled");Array$(".loading").show();Array

And once the process is over, we enable the button and hide the image: Array$(".button").removeAttr("disabled");Array$(".loading").hi de();Array

Here's the modified page:

Page 8 of 9

Array<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">Array<html>Array<head>A rray <script type="text/javascript" src="jquery-1.3.2.js"></script>Array <style>Array #result{Array width: 250px;Array height: 100px;Array border: 1px solid gray;Array }ArrayArray .loading{Array display: none;Array }Array </style>Array <script type="text/javascript">Array $(document).ready(function() {Array $("#input_form").submit(function(){Array $(".button").attr("disabled", "disabled");Array $(".loading").show();Array $.ajax({Array url: 'result2.php',Array dataType: "json",Array success: function(data) {Array $("#timestamp").html(data.timestamp);Array $("#hour").html(data.hour);Array $("#day").html(data.day);Array $(".button").removeAttr("disabled");Array $(".loading").hide();Array }Array });Array return false;Array });Array });Array </script>Array</head>Array<body>ArrayArray<form id="input_form" action="?">Array <input type="submit" value="request data" class="button"> <img src="loading.gif" border="0" class="loading">Array</form>ArrayArray<div id="result">Array The current timestamp is: <span id="timestamp"></span><br>Array That corresponds to hours: <span id="hour"></span><br>Array of day: <span id="day"></span>Array</div>Array</body>Array</html>Array

Obviously our request is so simple that probably it won't even be aware of the appearance of the image and deactivation of the button. But if you want to test it, you can add in the beginning of result2.php this instruction. Arraysleep(2);Array

Page 9 of 9

The execution will be suspended for two seconds stimulating thus a slow server (like in this example).

Conclusion
In this article we have seen two simple examples of asynchronous calls by making use of jQuery. As you could notice, the use of this framework allows us to reach our goal with only a few and clear lines of code. In the next article the menu will be a lot tastier: we'll see a more advanced application and very popular, that is concatenation in select. Let me explain: remember those forms in which you are required for example to choose a car brand through a select and once made your choice the second select (in which you are asked to choose the model) is populated dynamically (and even magically a little bit) with the models of the brand you have chosen? Well, we are going to do something like that. You expected the implementantion of ajax to be difficult, didn't you?

You might also like