Professional Documents
Culture Documents
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?
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.
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.
As you can see it's simply about printing on video the data passed from the form inside a phrase.
Page 3 of 9
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
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.
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
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.
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
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?