Create Your First AJAX Request (Part Three)

The complete script can be downloaded here AjaxRequest (30.91 KB) Create your first AJAX Request :)

In the last part of this series, we’ll create ’showdetails.js’. This will turn our web page into a AJAX-powered web page!

In the first part we created the XMLHttpRequest Object. Now we need to create an instance of it.

var req = new getRequestObj();

The XMLHttpRequest Object has methods and properties that enable us to communicate with the server. Don’t worry if these seem a bit daunting at first, the final JavaScript is very simple. In our example, we only need to use two of the methods, ‘open()’ and ’send()’.

open()

This opens the connection to the server. It takes 3 parameters; the method of sending (POST or GET), the url to send the request to and a boolean value (true or false). The last parameter states whether you want the request to be asynchronous. Usually you will want this to be true (the whole reason for using AJAX in the first place). Here’s an example:

req.open("GET", 'myscript.php', true);

send()

Funnily enough, this sends our request to the server. If you’re using POST as the request method, you would use this to add parameters to your request, such as values from a form. If you’re using GET, set it to ‘null’.

req.send(null);

Now let’s look at the properties we’ll be using:

readyState

This let’s us know what state our request is at. The readyState can be anywhere from 0 – 4, ‘0′ being uninitialised and ‘4′ being complete. We wait for ‘4′ before updating the page.

status

This returns the HTTP response code for the url we requested. We want ‘200′ before updating the page.

onreadystatechange

This defines a function to be called when the ‘readyState’ changes.

responseText

This returns the response from the server as a string of plain text.

With a little understanding of the methods and properties, let’s create our ’showDetails’ function:

function showDetails(user) {
	document.getElementById('user_details').innerHTML = 'Loading...<img src="images/loader.gif" alt="loading" />';
	var req = new getRequestObj();
	if (req) {
		req.onreadystatechange = function() {
			doAjax(req);
		};
		req.open("GET", 'getajaxuser.php'+user, true);
		req.send(null);
	}
}

Walking through the above script. The function takes a parameter (user) which will be supplied from the ‘href’ attribute (more on that later). We place a ‘loading’ gif inside the ‘user_details’ div. We create a new XMLHttpRequest Object. If the object was successfully created, we define a callback function for ‘onreadystatechange’ (doAjax(), which we’ll create next). We open the connection to the server, passing it the php script to send to (which we also need to create). Finally, we send the request.

The callback function, doAjax() is very simple. It checks to make sure that ‘readyState’ is ‘4′ and ’status’ is ‘200′. If so, it inserts responseText into the ‘user_details’ div.

function doAjax(req) {
	if( (req.readyState == 4) && (req.status == 200)) {
		document.getElementById('user_details').innerHTML = req.responseText;
	}
}

In the ‘open()’ method, we’ve specified ‘getajaxuser.php’+user as the url to send to. This is almost identical to the php we used in ‘index.php’ but instead of storing the $output variable, it echoes it. This will be the ‘responseText’ property in our doAjax() function.

getajaxuser.php

<?php
include ('cnx.php');
$user_id = (int) $_GET['user'];
$query = "SELECT * FROM `users` WHERE `users`.`user_id` = '$user_id' LIMIT 1";
$result = mysql_query($query) OR die ('Could not perform the query: ' . mysql_error() );
if(mysql_num_rows($result) ==1) 
{
	$row = mysql_fetch_array($result,MYSQL_ASSOC);
	$output .= '<ul>';
	$output .= '<li><h3>' . ucfirst($row['user_name']) . '</h3>';
	$output .= '<img src=' . $row['user_avatar'] . ' /><p>' . $row['user_interests'] . '</p></li>';
	$output .= '</ul>';
}
else Create Your First AJAX Request (Part Three)
{
	$output = '<p>There isn\'t a user with that name</p>';
}
echo $output;	
?>

Finally, we need to call showDetails() when a link is clicked. We’ll wrap this in a window.onload event.

window.onload = function () {
	var userContainer = document.getElementById('users');
	var links = userContainer.getElementsByTagName('a');
	for (var i = 0; i< links.length; i++) {
		links[i].onclick = function() {
			var userid = this.href.substr(this.href.indexOf("?"));
			showDetails(userid);
			return false;
		}
	}
}

The first two lines target the links in our ‘users’ div. We then loop through them and assign an ‘onclick’ event function. The important lines are these:

var userid = this.href.substr(this.href.indexOf("?"));
showDetails(userid);
return false;

The first line searches the ‘href’ attribute and returns everything after (and including) the question mark (the user parameter). We then pass this parameter to our showDetails function. ‘return false’ stops the browser from following the natural ‘html’ link

Your complete showdetails.js should look like this:

function showDetails(user) {
	document.getElementById('user_details').innerHTML = 'Loading...<img src="images/loader.gif" alt="loading" />';
	var req = new getRequestObj();
	if (req) {
		req.onreadystatechange = function() {
			setTimeout(function(){doAjax(req)},500);
			// normally doAjax(req);
		};
		req.open("GET", 'getajaxuser.php'+user, true);
		req.send(null);
	}
}
 
function doAjax(req) {
	if( (req.readyState == 4) && (req.status == 200)) {
		document.getElementById('user_details').innerHTML = req.responseText;
	}
}
 
window.onload = function () {
	var userContainer = document.getElementById('users');
	var links = userContainer.getElementsByTagName('a');
	for (var i = 0; i< links.length; i++) {
		links[i].onclick = function() {
			var userid = this.href.substr(this.href.indexOf("?"));
			showDetails(userid);
			return false;
			}
		}
	}

Phew!!! All done :) I hope this final post wasn’t too long for you. If you’ve followed this, give yourself a large pat on the back! If you can’t be bothered to ‘cut and paste’, I’ve made the whole thing available to download. Just click here AjaxRequest (30.91 KB) Create your first AJAX Request :)

Feed IconFollow me on Twitter





2 Responses to “Create Your First AJAX Request (Part Three)”

  1. woop! Part 3. Once again, consider it dugg! Keep up the good work sir!

  2. [...] Read more here: Create Your First AJAX Request (Part Three) | ElanMan [...]

Leave a Comment







XHTML: You can use the following tags in your comments: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">