Two AJAX Walkthroughs: a File Fetcher and MySQL Fetcher

AJAX (Asynchronous JavaScript and XML) is one of the coolest things you can do with JavaScript: it lets you update web pages after they’re loaded. This process might not mean much to you if you’re thinking only as a programmer. But, think about the convenience AJAX delivers to your typical web user: less waiting.

When you combine an AJAX-powered JavaScript page with PHP, you can pull in data from any part of the web — a great way of detouring the same-domain security restriction hard-coded into browsers. But you can also complete important tasks with just JavaScript code.

Fetch web content from your site

Try this example script, which fetches the content of a web page whose filename is entered by the user in an HTML text box. The AJAX phenomenon will be immediately apparent when you open this page in your browser: as you’re typing the filename, the JavaScript makes asynchronous (AJAX) requests to the server to fetch the file’s content and then displays that content.

Let’s shoot first and ask questions later. Here’s the code:

<html>

<head>

<script type=&quot;text/javascript&quot;>

var obPageFetcher=null;

function fetchPage() {

    var sUrl = document.getElementById(&quot;filename&quot;).value;

    obPageFetcher=new XMLHttpRequest();

    obPageFetcher.onreadystatechange=function () {

if (obPageFetcher.readyState==4) {

/* A readyState of 4 means

&quot;all data has been received.&quot;

See the &quot;XMLHTTPRequest object&quot; on MSDN.com

*/

if (obPageFetcher.status==200){

/* A status of 200 means

&quot;OK,&quot; successful request.&quot;

See above note.

*/

document.getElementById('divContent').innerHTML=

obPageFetcher.responseText;

} else {

document.getElementById('divContent').innerHTML=

obPageFetcher.statusText;

}

}//on readyState==4

}//state_Change call back;

obPageFetcher.open(&quot;GET&quot;,sUrl,true);

obPageFetcher.send(null);

}// fetchPage()

</script>

</head>

<body>

<input onkeyup=&quot;fetchPage()&quot; type=&quot;text&quot; id=&quot;filename&quot;

style=&quot;border-color:blue&quot; size=&quot;40&quot;

value=&quot;http://www.<TYPE_YOUR_DOMAIN_NAME_HERE>.com/index.htm&quot;>

<br>

<div id=&quot;divContent&quot; ></div>

</body>
</html>

You’ll need a web hosting service to upload this page to. Once you have one, enter your domain’s name in place of the text in the script.

Run this script by uploading it to your web host’s server, then download the page into your browser. Start typing in the text box and you’ll notice immediately that the content changes based on what you’re typing. Enter in valid filenames for files in your domain (e.g. “index.htm”) and the script will load the HTML content of those files into your page below the text box.

How it works

We’ll get to the sexy AJAX stuff in a moment, but let’s look at the code’s parts in a logical order. First, notice the page’s main DOM (document object model) elements inside the tag: there’s only a text box
and a

,/code> to hold the fetched content.

The
element has an event listener attached to its “onkeyup” event; every time you lift your finger off any key while in the text box, that event listener function (fetchPage) is going to be called. So far, there’s nothing AJAX-y about the code, but that’s coming in the fetchPage() function.

Fetch page

The fetchPage callback function’s main job is to prepare for and then make the asynchronous request to the server. To do this preparation, fetchPage needs to tell the XMLHTTPRequest object, which does the actual asynchronous request, what function to call when the server responds. In other words, fetchPage is defining a callback function to hand to the XMLHTTPRequest object. You can see that function in the statement obPageFetcher.onreadystatechange=function…. (If this statement looks goofy to you, don’t blame AJAX, but JavaScript, which allows nameless (AKA “anonymous”) functions in its syntax.)

The guts of the callback function

The callback function checks on a couple of status properties (“readyState” and “status”) before assigning the real guts of the server response, inside property “responseText,” to the output DOM element mentioned earlier (“divContent”). Describing the callback function first is a bit like putting the egg before the chicken, in terms of program execution: on the first call to fetchPage, we’re only defining the anonymous callback function, not actually calling it. After we define the callback function, we open up (statement “obPageFetcher.open(…)” ) and send (statement “obPageFetcher.send(…)”) the request to the server.

Example two: Use AJAX to do a database pull

If you know how to do a basic SELECT fetch from a MySQL database using PHP, you can apply that knowledge to do the fetch asynchronously with AJAX. If you’re not MySQL savvy yet, don’t fret: see the Resources section of this article to get the know-how. Plus, do get the details of connecting to your MySQL database from the tech support people at your web host–you’re paying them to support you.

Create a “movies” table on a MySQL database on your server. Define the fields in the table as follows:

  • title: varchar(30)
  • director: varchar(30)
  • year: int

Enter the following sample data in that table, corresponding to the fields just given. Don’t enter the commas.

  • star wars, lucas, 1977
  • excalibur, boorman, 1980

Create a PHP script from the following code and call the script “phpMySQLFetch.php”

Upload the file to your server, then make the following changes to the AJAX script given earlier:

<?php

mysql_connect(&quot;<YOUR_MYSQL_DATABASE_NAME>&quot;, &quot;<YOUR MYSQL LOGIN>&quot;, &quot;<YOUR MYSQL PASSWORD>&quot;) or die(mysql_error());

mysql_select_db(&quot;<YOUR DATABASE NAME>&quot;) or die(mysql_error());

$sTitle = $_GET[&quot;title&quot;];

$sqry = 'SELECT * FROM `movies` WHERE `title` LIKE CONVERT(_utf8 '%'.$sTitle.'%' USING latin1) COLLATE latin1_swedish_ci';

$data = mysql_query($sqry)

or die(mysql_error());

while($info = mysql_fetch_array( $data ))

{

Print $info['title'].&quot;, &quot;.$info['director'].&quot;, &quot;.$info['year'].'<br>';

}

?>

Change the fetchPage function in the HTML page so it starts like this:

function fetchPage() {
    sUrl = "phpMySQLFetch.php?title=" +
    document.getElementById('title').value;
    ... // The rest is the same as the first example

Change the element to look like this:

<body >
<input type=&quot;text&quot; size=&quot;40&quot; name=&quot;title&quot; id=&quot;title&quot; onkeyup=&quot;fetchPage()&quot;>
<br>
<div id=&quot;divContent&quot; ></div>
</body>

Upload the revised HTML page to the same folder on your server that contains the PHP script, then download the HTML page into your browser. Start typing the names of one of the movies (e.g. “star wars,” “excalibur”) in the text box, and watch the AJAX code dynamically fill in the page with the rest of the info for that movie.

Experiment

As mentioned before, combining PHP server code with JavaScript will really show you the power of AJAX, because the PHP can go into the proverbial “where no man has gone before,” — all over the web, in other words, to fetch content. To get started with that, start digging into PHP by reading Introduction to PHP . Then, adapt the script in this article so that it calls and retrieves content from your PHP script.

References

W3Schools’ AJAX Tutorial

Resources

PHP MySQL Tutorial

Got something to say? Go for it!