jQuery Ajax Example

In a previous article I’ve written some about Ajax and how it can be useful. In this article I’ll give a detailed and simple code example to help you understand how you might use the jQuery “ajax” method. We will create the front end of a web page where two or more visitors can chat.

If you are following along with this example, start by downloading the jQuery Javascript library at jQuery.com. Save the js file under your webroot folder (www or public_html on Linux) as jquery.js.

If you don’t know which version of the jQuery file to download (minified VS uncompressed) the minified version of the file is generally preferred since it saves drive space and bandwidth. But if you have a desire to see the inner workings of the jQuery code you should download the uncompressed version since it is easier to read.

Next, create a new empty file called “index.html” in your webroot folder, and paste the following HTML inside it.

1
2
3
4
5
6
7
8
<html>
<head>
 
</head>
<body>
 
</body>
</html>

Now that we have the basics of the webpage created, we need to include a reference to the jQuery Javascript file. This will allow us to call jQuery’s methods. Add the following in the head section of your HTML.

1
<script type="text/javascript" src="jquery.js"></script>

The next step is to create a container for the chat messages, and an input box where visitors can type their messages. We will also need a button to submit the chat message. Insert the following markup between the “body” tags.

1
2
3
<div id="allMessages"></div>
<input type="text" id="myMessage" />
<button id="sendMessageButton">Send</button>

We should style our layout a bit to make it look somewhat decent. Add this to the “head” section.

1
2
3
4
5
6
7
8
9
10
<style type="text/css">
    #allMessages{
        width:300px;
        height:250px;
        border:solid black 1px;
    }
    #myMessage{
        width:200px;
    }
</style>

Let’s now bite into the meat and make our chat page functional. When a user clicks on the “Send” button we need to send their message to the web server where it can be stored and then read back to other users’ web browsers. jQuery has a convenient method for handling clicks. We will add some code to the “head” tag.

1
2
3
4
5
<script type="text/javascript">
    $('#sendMessageButton').click(function(){
 
    });
</script>

Without delving into the basics of jQuery I’ll simply say that the code above defines an anonymous click handler for our “sendMessageButton” button element. (Visit jQuery.com to learn the basic use of jQuery).

We have our click handler so we are finally ready to grab the user’s chat message and send it off to the web server using an Ajax call. Update your Javascript code to look like this.

1
2
3
4
5
6
7
8
$('#sendMessageButton').click(function(){
    $.ajax({
        type: "POST",
        url: "process_message.php",
        data: { message: $('#myMessage').val() },
        contentType: "application/json; charset=utf-8"
    });
});

The code above is our jQuery Ajax call. There are quite a few parameters that can be set with the “ajax” method, but for this example we will focus on only a few. We are sending the message as a “POST” to a PHP file on our server. Our “data” is sent in JSON format, as defined in the “contentType” option. This completes the part where a user sends a chat message!

The final part of this example is to get new messages from the server and display them in our “allMessages” div container. We will create a function that retrieves new messages on approximately 5 second intervals. We could use the setInterval function, but to avoid timing issues we will use the setTimeout function instead. Add the following code to our script tag in the “head”.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
var timestamp = 0;
$(document).ready(function(){
    // Get messages after 5 seconds (5000 milliseconds).
    setTimeout("getMessages",5000);
});
function getMessages(){
    $.ajax({
        type: "GET",
        url: "get_messages.php",
        data: { timestamp: timestamp },
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(response){
            // The data we are looking for will be in the "d" attribute of the "response" object.
            timestamp = response.d.timestamp;
            var messagesHtml = $('#allMessages').html() + response.d.messagesHtml;
            $('#allMessages').html(messagesHtml);
 
            // Set the timer to get messages in 5 more seconds.
            setTimeout("getMessages",5000);
        }
    });
}

This is a bit to chew on so I’ll help you out. First we create a timestamp variable which will hold the timestamp sent from the server on each message request. Once we have a value from the server we can send it back on the next request, acting as a marker so the server knows that it should only send new messages since that timestamp. This should prevent the same messages being sent to the front end over and over again.

Next we call the jQuery “ready” method on the “document” object. This serves the same purpose as “document.onload”, telling the web page to fire off the handler once the page document has completely loaded. Our “ready” handler sets a timeout to get our first set of messages in 5 seconds.

When our timeout is triggered the “getMessages” function is executed. We have our familiar jQuery “ajax” function call, but this time our options are different. One thing to note is that we’ve set the “dataType” to “json”, telling jQuery to parse the response from the server into a Javascript object. The “success” option defines an anonymous handler. We get the response from the server, reset our “timestamp” variable and update the contents of our “allMessages” div with the latest chat messages from the server. Finally, a new timeout is set to check for messages again in 5 more seconds.

Our complete web page should look like this.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
<html>
<head>
    <script type="text/javascript" src="jquery.js"></script>
    <style type="text/css">
        #allMessages{
            width:300px;
            height:250px;
            border:solid black 1px;
            overflow-y: scroll;
            overflow-x: scroll;
        }
        #myMessage{
            width:200px;
        }
    </style>
    <script type="text/javascript">
        $('#sendMessageButton').click(function(){
            $.ajax({
                type: "POST",
                url: "process_message.php",
                data: { message: $('#myMessage').val() },
                contentType: "application/json; charset=utf-8"
            });
        });
 
        var timestamp = 0;
        $(document).ready(function(){
            // Get messages after 5 seconds (5000 milliseconds).
            setTimeout("getMessages",5000);
        });
        function getMessages(){
            $.ajax({
                type: "GET",
                url: "get_messages.php",
                data: { timestamp: timestamp },
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(response){
                    // The data we are looking for will be in the "d" attribute of the "response" object.
                    timestamp = response.d.timestamp;
                    var messagesHtml = $('#allMessages').html() + response.d.messagesHtml;
                    $('#allMessages').html(messagesHtml);
 
                    // Set the timer to get messages in 5 more seconds.
                    setTimeout("getMessages",5000);
                }
            });
        }
    </script>
</head>
<body>
    <div id="allMessages"></div>
    <input type="text" id="myMessage" />
    <button id="sendMessageButton">Send</button>
</body>
</html>

This should give you some ideas of your own how Ajax can be used on your own web projects. Good luck and have fun!