Client-side Code (jQuery)
Now, on to the jQuery front end. First, we need to declare the timestamp of the current message as 0, and call the function that loads the messages from the server:
timestamp = 0;
updateMsg();
Next, we’ll write the code for the form submission. jQuery allows us to add an event hook for the form’s submit event, as though we were adding an onSubmit
event within the HTML itself, except that we don’t have to touch the HTML. Here’s the submit event:
$("form#chatform").submit(function(){ /* Code */ });
Here we’re using CSS selector syntax to refer to the form element with an id
of 'chatform'
. As soon as we’re into the form submission code, we can fire off a POST request to the server using jQuery’s $.post
. Within the call to $.post
, we can select the values of the form elements on the page on the basis of their id
s, as we determined earlier. With this in mind, we can dive into our Ajax call:
$.post("backend.php",{ message: $("#msg").val(),
name: $("#author").val(), action: "postmsg", time: timestamp }, function(xml) {
Notice that the array of parameters to be passed in the request is enclosed with curly braces. If you have more parameters, simply separate them with commas and use the format presented here, JSON-style. You can also use jQuery’s Ajax functions to send a GET request that expects a JSON-style response, and have jQuery convert the response text into an easy-to-use format. Bear in mind, though, that this capability is only available for the GET request type, not the POST request type we use for our chat system. As such, we’ll stick with plain XML for the moment.
Now, let’s look at handling the XML response. Since we’re all for code reuse, we’ll create a function that handles the XML and call it now:
addMessages(xml);
We’ll write this function later so that we can finish off the form submission event code. The code we’ve written so far is all we need for our $.post
callback function, so we can close it off and add a return false; line. This line fails using the standard browser form submission error code. The browser doesn’t send the user to another page to submit the form — we’ve already handled the form submission, so the browser doesn’t need to. Here’s the event code in its entirety:
$("form#chatform").submit(function(){
$.post("backend.php",{
message: $("#msg").val(),
name: $("#author").val(),
action: "postmsg",
time: timestamp
}, function(xml) {
addMessages(xml);
});
return false;
});
Now, let’s get back to the addMessages()
function, which handles the response xml. It’s quite simple, making use of jQuery’s DOM manipulation and traversing functions. Remember that I mentioned the status code before? Now’s the time to handle it:
if($("status",xml).text() == "2") return;
I haven’t mentioned context in jQuery yet. The XML in this function call tells jQuery to look not inside the document HTML, but in the XML that the server sent us.
That line of code checks for a status code of 2, representing a successful request that resulted in us having no new messages to add to the window. The 'return'
keyword terminates the function call. Next, we set the timestamp to the timestamp in the XML:
timestamp = $("time",xml).text();
Again, this fetches the text value of the <time>
tag in the XML.
Now we can move on to jQuery’s array iteration function, each()
. jQuery has an interesting way of handling array iteration. We use a standard selector statement, and the each()
function is passed one parameter — a function to handle each instance of the matched elements. In this case, the elements are the instances of the <message>
tag in the server response, each instance representing a message to be displayed. One parameter — the id
of the instance — is passed to the function. We can use this, with jQuery’s get()
function, to grab a new context — the actual XML of the <message>
tag. This is how we select it:
$("message",xml).each(function(id) {
message = $("message",xml).get(id);
We can then select elements by passing the context 'message'
to the jQuery / $
function. Now that we have all the data we need, we must add it to the top of the message window on the page. The message window has the id 'messagewindow'
, so we select it using $("#messagewindow")
and use the prepend()
function to add our data:
$("#messagewindow").prepend("<b>"+$("author",message).text()+
"</b>: "+$("text",message).text()+
"<br />");
That’s all there is to it! Putting it all together, here’s the code for the function:
function addMessages(xml) {
if($("status",xml).text() == "2") return;
timestamp = $("time",xml).text();
$("message",xml).each(function(id) {
message = $("message",xml).get(id);
$("#messagewindow").prepend("<b>"+$("author",message).text()+
"</b>: "+$("text",message).text()+
"<br />");
});
}
Finally, we need the updateMsg
function we called at the very beginning of our code. This function has to query the server for new messages, and call the above addMessages
function with the response. It also has to set a timeout to call itself after a set period of time, which makes the chat window update automatically. To begin, we don’t need to submit anything to the server besides a timestamp, so this is our $.post
call:
$.post("backend.php",{ time: timestamp }, function(xml) {
As I noted before, we also need to remove the loading message at this point, so we call jQuery’s remove function on the span:
$("#loading").remove();
Then, we’ve received our xml response in the object 'xml'
, so we pass it to our addMessages
function:
addMessages(xml);
We round it off with a call to the JavaScript setTimeout()
function, which executes specified code after a specified interval. Here’s the whole function put together:
function updateMsg() {
$.post("backend.php",{ time: timestamp }, function(xml) {
$("#loading").remove();
addMessages(xml);
});
setTimeout('updateMsg()', 4000);
}
Putting it All Together
Now we can put all of the pieces of the puzzle together. The code is, as I mentioned, available in this downloadable zip file. However, you can peruse it here, where I’ve added a bit of HTML and CSS for layout:
<html>
<head>
<title>Ajax with jQuery Example</title>
<script type="text/JavaScript" src="jquery.js"></script>
<script type="text/JavaScript">
$(document).ready(function(){
timestamp = 0;
updateMsg();
$("form#chatform").submit(function(){
$.post("backend.php",{
message: $("#msg").val(),
name: $("#author").val(),
action: "postmsg",
time: timestamp
}, function(xml) {
$("#msg").empty();
addMessages(xml);
});
return false;
});
});
function addMessages(xml) {
if($("status",xml).text() == "2") return;
timestamp = $("time",xml).text();
$("message",xml).each(function(id) {
message = $("message",xml).get(id);
$("#messagewindow").prepend("<b>"+$("author",message).text()+
"</b>: "+$("text",message).text()+
"<br />");
});
}
function updateMsg() {
$.post("backend.php",{ time: timestamp }, function(xml) {
$("#loading").remove();
addMessages(xml);
});
setTimeout('updateMsg()', 4000);
}
</script>
<style type="text/css">
#messagewindow {
height: 250px;
border: 1px solid;
padding: 5px;
overflow: auto;
}
#wrapper {
margin: auto;
width: 438px;
}
</style>
</head>
<body>
<div id="wrapper">
<p id="messagewindow"><span id="loading">Loading...</span></p>
<form id="chatform">
Name: <input type="text" id="author" />
Message: <input type="text" id="msg" />
<input type="submit" value="ok" /><br />
</form>
</div>
</body>
</html>
So, with 22 lines of JavaScript, eight lines of HTML, and around 50 lines of PHP, we now have a fully functional Ajax web application. Try it out, and integrate it into your own site. Build your own Ajax application, using these techniques and your own ideas. Take this code and modify it to build something new. If you aren’t comfortable with generating and handling XML, stick with using your web application to generate HTML, and using load()
to bring it to the client. Then, once you get the hang of it, try out an application that utilises the full power of XML using tag attributes and jQuery’s attr()
function — you’ll be amazed at just how powerful Ajax with jQuery can be.
If you enjoyed reading this post, you’ll love Learnable; the place to learn fresh skills and techniques from the masters. Members get instant access to all of SitePoint’s ebooks and interactive online courses, like jQuery Fundamentals.
Akash Mehta is a web developer and freelance writer specializing in web application development.