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.

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”.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
</head>
<body>

<form id="input_form" action="?">
    Insert name:<br />
    <input type="text" name="name" id="name"/><br />
    Insert last name:<br>
    <input type="text" name="lastname" id="lastname"/><br/ ><br/ >
    <input type="submit" value="send">
</form>

<div id="result"></div>

</body>
</html>

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:

<?php
echo "You have inserted the following data: Name-><strong>$_POST[name]</strong> and Last name-><strong>$_POST[lastname]</strong>. You have executed an asynchronous call!";
?>

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

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:

<head>
    <script type="text/javascript" src="jquery-1.4.1.js"></script> <!-- The version could be different -->
    <script type="text/javascript">
    $(document).ready(function() {
    //Here we will write the necessary code
    });
</script>
</head>

Let’s create now the necessary jQuery code which I am going to explain in detail below.

$("#input_form").submit(function(){
    var name = $("#name").attr('value');
    var lastname = $("#lastname").attr('value');
    $.post("result.php", {name:name,lastname:lastname}, function(data){
        $("div#result").html(data);
    });
return false;
});

So, in the first line we state:

$("#input_form").submit(function(){

In the element with id “input_form“, at the occurrence of “submit” event, execute this function.

In the second and third line:

var name = $("#name").attr('value');
var lastname = $("#lastname").attr('value');

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).

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:

$.ajax({
    url: 'result.php',
    type: "POST",
    data: "name="+name+"&lastname="+lastname,
    success: function(data) {
        $("div#result").html(data);
        }
});

As you can see $.ajax has a different and slightly more complex syntax. This as it 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).

<?php
$time = time();
$hour = date("H:i:s");
$day = date("j/n/Y");
echo "{'timestamp':'$time','hour':'$hour','day':'$day'}";
?>

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

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <script type="text/javascript" src="jquery-1.3.2.js"></script>
    <style>
        #result{
            width: 250px;
            height: 100px;
            border: 1px solid gray;
        }
    </style>
    <script type="text/javascript">
        $(document).ready(function() {
            // here we will write the function
        });
    </script>
</head>
<body>
<form id="input_form" action="?">
    <input type="submit" value="request data">
</form>

<div id="result">
    The actual timestamp is: <span id="timestamp"></span><br />
    which corresponds to time: <span id="hour"></span><br />
    of day: <span id="day"></span>
</div>
</body>
</html>

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.

$("#input_form").submit(function(){
    $.ajax({
    url: 'result2.php',
    dataType: "json",
    success: function(data) {
        $("#timestamp").html(data.timestamp);
        $("#hour").html(data.hour);
        $("#day").html(data.day);
        }
    });
return false;
});

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: “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

<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:

.loading{
    display: none;
}

Now at the occurrence of the submit event we disable the button and display the image:

$(".button").attr("disabled", "disabled");
$(".loading").show();

And once the process is over, we enable the button and hide the image:

$(".button").removeAttr("disabled");
$(".loading").hide();

Here’s the modified page:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <script type="text/javascript" src="jquery-1.3.2.js"></script>
    <style>
         #result{
            width: 250px;
            height: 100px;
            border: 1px solid gray;
        }

        .loading{
            display: none;
        }
    </style>
    <script type="text/javascript">
        $(document).ready(function() {
            $("#input_form").submit(function(){
                $(".button").attr("disabled", "disabled");
                $(".loading").show();
                $.ajax({
                    url: 'result2.php',
                    dataType: "json",
                    success: function(data) {
                        $("#timestamp").html(data.timestamp);
                        $("#hour").html(data.hour);
                        $("#day").html(data.day);
                        $(".button").removeAttr("disabled");
                        $(".loading").hide();
                        }
                     });
                return false;
                });
            });
    </script>
</head>
<body>

<form id="input_form" action="?">
    <input type="submit" value="request data" class="button"> <img src="loading.gif" border="0" class="loading">
</form>

<div id="result">
    The current timestamp is: <span id="timestamp"></span><br>
    That corresponds to hours: <span id="hour"></span><br>
    of day: <span id="day"></span>
</div>
</body>
</html>

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.

sleep(2);

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?

Master per Web Designer Freelance
In tutti questi anni abbiamo ricevuto centinaia di richieste di approfondimento sulle numerose tematiche del web design vissuto da freelance. Le abbiamo affrontate volta per volta. Ma ci siamo resi conto che era necessario fare qualcosa di più. Ecco perché è nato One Year Together, un vero e proprio master per web designer freelance che apre finalmente le porte al mondo del lavoro.
Scopri One Year Together »
[pdf]Scarica articolo in PDF[/pdf]
Tags: ,

The Author

Maurizio is married to the triad PHP - MySql - Apache and, not enough, he has a lover called jQuery. He has a blog where he tries to describe in detail all of "his lovers". His real specialty is the realization of large business application, altough he never refuses the commitment of a website.

Author's web site | Other articles written by

Related Posts

You may be interested in the following articles:

5 comments

  1. Inder Singh

Trackback e pingback

  1. Tweets that mention Do you want to implement ajax features but you don’t know how? | Your Inspiration Web -- Topsy.com
    [...] This post was mentioned on Twitter by V. Tavares (E-Goi) and Tom Bangham, Your Inspiration Web. Your Inspiration Web …
  2. How to create chained select with PHP and jQuery? | Your Inspiration Web
    [...] let’s add something else. Do you remember the question on the usabilty faced in the previous article on ajax? Good, …
  3. You are now listed on FAQPAL
    Do you want to implement ajax features but you don’t know how?... Ajax is always more and more diffused and common …
  4. Element with jquery |Avnish Namdev
    [...] Do you want to implement ajax features but you don’t know how? [...]

Leave a Reply

Current month ye@r day *