Wednesday, October 31, 2007

Howto Display Records from a Database without Refreshing the Entire Page, PHP & AJAX

This post address a common question found on on AJAX and PHP forums.

Howto grab the newest records from the database and display them without the traditional meta refresh?
Or
Howto display records from a database without refreshing the entire page?

The requirements:
A basic understanding of AJAX. Get started with AJAX here: http://developer.mozilla.org/en/docs/AJAX:Getting_Started
PHP
MySQL
A dataset

I am going to use the mozilla developer docs as a reference point.

The first step is to create a HTTP request. Before we do that we need to figure out the browser that the user is running.

If the browser is Internet Explorer, call the ActiveXObject
else, call the XMLHttpRequest();
// This includes all browsers other than Microsoft Internet Explorer.
//Mozilla, Safari etc


// Create the HTTP request
function createRequestObject()
{
var browser;
if (window.XMLHttpRequest)
{
// Mozilla, Safari, ...
browser = new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
browser = new ActiveXObject("Microsoft.XMLHTTP");
}
return browser;
}

var httpRequest = createRequestObject();


Once we've got the HTTP request setup, our next step is to grab the contents from the database. It is here that we set the time interval or the frequency on when the updated content is displayed.

We're going to call a PHP script get_records.php that actually grabs the dataset from the database. More on the PHP script later.

The time interval is set to 300000 milli seconds, 5 minutes

Convert minutes to seconds:
5 minutes = 5 x 60 seconds = 300 seconds

Convert seconds to milli seconds:
300 seconds = 300 x 1000 milli seconds = 300000 milli seconds

Note the exception handler below. The alert popup box will appear if there was an error. You can comment out that line later.

function displayOutput()
{
try
{
setTimeout("displayOutput()", 300000); // Recursive JavaScript function calls displayOutput() every 5 minutes, 1800 seconds
httpRequest.open('GET', 'get_records.php', true);
httpRequest.onreadystatechange = handleResponse;
httpRequest.send(true);
}
catch( e1 )
{
// Unable to open file
alert('Caught Exception: ' + e1.description);
}
}

The next step is to handle the data. We've made the HTTP request, we've called the PHP script, we've got the data. What are we going to do with the data?

If everything went well, readystate should be == 4(complete) and httpRequest.status should be == 200. All ok .. Proceed to set the innerHTML with the data.

Read about innerHTML:
http://msdn2.microsoft.com/en-us/library/ms533897.aspx


function handleResponse()
{
try {
if (httpRequest.readyState == 4) {
if (httpRequest.status == 200) {
//alert(httpRequest.responseText);
document.getElementById("data").innerHTML = httpRequest.responseText;
} else
{
alert('There was a problem with the request.');
}
}
}
catch( e2 )
{
alert('Caught Exception: ' + e2.description);
}
}


Our final step is to display the data:

\<\body onload\=\"displayOutput\(\)\;\"\>
\<\div id\=\"data\"\>\<\/div\>
\<\/body\>

To be continued ...

No comments: