Create Your First AJAX Request (Part Two)
An example of what you’re creating can be seen here.
The complete script can be downloaded here AjaxRequest (30.91 KB) Create your first AJAX Request
In the first part, we created a function, getRequestObj(), that we can now use to initiate a new XMLHttpRequest object. This is as simple as…
var myReq = new getRequestObj();
However,it’s important to remember that JavaScript should always be added to the page to enhance the page. So with that in mind, we’ll create the basic html and php that works without any JavaScript involved. This ensures that the page will still be functional for those users without JavaScript enabled (albeit without the ajax slickness). We’ll also create a simple MySQL table to pull the data from. In fact, let’s do that first. Run this script inside your mysql client (phpMyadmin) or alternatively through a php script:
CREATE TABLE `users` ( `user_id` INT(3) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, `user_name` VARCHAR(20) NOT NULL, `user_interests` TEXT NOT NULL, `user_avatar` VARCHAR(40) NOT NULL)
This is pretty straight forward. Obviously, you’ll need to populate the table with your own data. The ‘user_avatar’ field needs to hold a path to the image on the file system (for example, ‘images/myavatar’). Now for the html:
index.php
<?php include ('cnx.php'); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>Show Dynamic Details With Ajax</title> <link rel="stylesheet" href="css/style.css" type="text/css" /> <script src="xhrobj.js" type="text/javascript"></script> <script src="showdetails.js" type="text/javascript"></script> </head> <body> <div id="wrapper"> <h1>Show User Details With Ajax</h1> <div id="users"> <h2>Users</h2> </div> <div id="user_details"> </div> </div> </body> </html>
This is a simple page consisting of a ‘wrapper’ div which contains 2 other divs, ‘users’ and ‘user_details’. At the moment, both of these divs are empty. Notice the php code at the very start of the page:
<?php include ('cnx.php'); ?>
This is the script that connects to our database:
cnx.php
<?php DEFINE ('DB_USER', 'dbuser'); DEFINE ('DB_PASSWORD', 'dbpassword'); DEFINE ('DB_HOST', 'dbhost'); DEFINE ('DB_NAME', 'dbtable'); $dbc = @mysql_connect (DB_HOST, DB_USER, DB_PASSWORD) OR die ('Could not connect to MySQL'); @mysql_select_db (DB_NAME) OR die ('Could not select the database'); ?>
Again, you’ll need to use your own database details here!
To populate the ‘users’ div with a list of users, we’ll query the database. Place the following code inside the ‘users’ div just after the level 2 heading:
<?php $query = "SELECT `user_id`, `user_name` FROM `users` ORDER BY user_id"; $result = mysql_query($query) OR die ('Could not perform the query'); if ($result) { echo '<ul>'; while ($row = mysql_fetch_array($result,MYSQL_ASSOC)) { echo'<li><a href="index.php?user=' . $row['user_id'] . '" title="View my profile">' . ucfirst($row['user_name']) . '</a></li>'; } echo '</ul>'; } ?>
This produces a list of user’s names. Each one is a link back to ‘index.php’ with that user’s ‘user_id’ passed as a parameter (for example, ‘index.php?user=1′).
To display a user’s info, we need to check for the ‘user’ parameter using the $_GET superglobal. Place the following code at the top of the page just after the line that includes ‘cnx.php’:
$output = FALSE; if (isset($_GET['user'])) { $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'); 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 { $output = '<p>There isn\'t a user with that name</p>'; } }
This performs a simple query that pulls out the data for the relevant user. It then builds a list containing the user’s details and assigns it to a variable called $output. If a user doesn’t exist with that user_id, $output contains an error message instead.
Inside the ‘user_details’ div, we check for the existence of $output. If it exists, we echo it to the page:
<div id="user_details"> <?php if ($output) {echo $output;} else {echo '<p>The user\'s profile details will appear here.</p>';} ?> </div>
After all of that, your final ‘index.php’ should look like the following:
index.php
<?php include ('cnx.php'); $output = FALSE; if (isset($_GET['user'])) { $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'); 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 { $output = '<p>There isn\'t a user with that name</p>'; } } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>Show Dynamic Details With Ajax</title> <link rel="stylesheet" href="css/style.css" type="text/css" /> <script src="xhrobj.js" type="text/javascript"></script> <script src="showdetails.js" type="text/javascript"></script> </head> <body> <div id="wrapper"> <h1>Show User Details With Ajax</h1> <div id="users"> <h2>Users</h2> <?php $query = "SELECT `user_id`, `user_name` FROM `users` ORDER BY user_id"; $result = mysql_query($query) OR die ('Could not perform the query'); if($result) { echo '<ul>'; while ($row = mysql_fetch_array($result,MYSQL_ASSOC)) { echo'<li><a href="index.php?user=' . $row['user_id'] . '" title="View my profile">' . ucfirst($row['user_name']) . '</a></li>'; } echo '</ul>'; } ?> </div> <div id="user_details"> <?php if ($output) {echo $output;} else {echo '<p>The user\'s profile details will appear here.</p>';} ?> </div> </div> </body> </html>
All that remains is to add some simple styling:
style.css
* { margin:0; padding:0; } body { text-align:center; } #wrapper { width:760px; margin: 10px auto; text-align:left; } h1 { text-align:center; color:#555; margin-bottom:10px; } h3 { color:#017dc7; margin-bottom:10px; } ul { list-style:none; } li { margin:10px; } p { color:#555; } a { text-decoration:none; color:#000; } a:hover { color:#f00; } #users { width:210px; height:300px; padding:20px; float:left; background:#dee9f0; } #user_details { width:462px; height:292px; padding:20px; border:4px dashed #dee9f0; float:right; }
We now have a functional web page. In the next part we’ll add the ajax functionality by creating ’showdetails.js’
An example of what you’re creating can be seen here.


Nice article Ben
Dugg!
Fantastic tutorial – One I’ll definitely be making use of in the future.
Thanks for posting
Also Dugg!
[...] For Full Reference Source: http://www.elanman.co.uk/2009/07/create-your-first-ajax-request-part-two/ [...]