Practical Web Programming

Friday, January 16, 2009

Simple PHP and Ajax Tutorial

When I was beginning web development, Ajax was all blur to me. Whenever I need Ajax functionality for my PHP project, I would go to the web and search to similar Ajax examples that fit need. Although today I'm not yet a master of this WEB 2.0 technique, I can say I passed the beginner stage.

In PHP, a simple, yet powerful implementation of Ajax is querying and displaying the result of a database query. This makes your web application run faster than just pure PHP because the browser don't have to load.

This simple PHP and Ajax tutorial is composed of three files, namely, index.php, ajax.js and ajax.php. I will be using the database from this post.

Here's the index.php. This file contains the HTML codes and the container in which the result of the query will be displayed.

<html>

<head>
<title>A Simple PHP-Ajax Tutotial</title>
<script src="ajax.js"></script>
</head>

<body>

<br/><input type='button' value='Query' onclick='queryDb()' name='Query' /><br/>

<div id='container'></div>

</body>
</html>


The ajax.js file contains the Javascript code.

//CREATE A VARIABLE THAT WILL HOLD THE XMLHttpRequest OBJECT
request = null;

//THIS FUNCTION WILL CREATE AN INSTANCE OF XMLHttpRequest OBJECT
AND RETURN IT TO THE CALLING FUNCTION
function GetXmlHttpObject()
{
var xmlHttp=null;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
//Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}

//THIS FUNCTION WILL CALL THE GetXmlHttpObject() FUNCTION AND THE ajax.php PAGE
function queryDb()
{
//DISPLAY THE 'LOADING' TEXT IN THE DIV CONTAINER
document.getElementById("container").innerHTML = "Loading";
//CREATE AN INSTANCE OF XMLHttpRequest OBJECT
request = GetXmlHttpObject();
//SET queryDone FUNCTION TO THE onreadystatechange EVENT
request.onreadystatechange = queryDone;
//OPEN THE PHP PAGE USING THE POST METHOD
request.open("POST", "ajax.php", true);
//SEND THE REQUEST
request.send(null);
}

//HELPER FUNCTION FOR queryDb()
function queryDone()
{
if (request.readyState == 4)
{
if (request.status == 200 || request.status == 304)
{
//GET THE RESPONSE FROM THE PHP PAGE
results = request.responseText;
//DISPLAY THE RESPONSE IN THE DIV CONTAINER
document.getElementById("container").innerHTML = results;
}
else
{
//IF A ERROR OCCUR, DISPLAY IT IN THE DIV CONTAINER
document.getElementById("container").innerHTML = "ajax error:\n" + request.statusText;
}
}
}


The ajax.php file contains the PHP code that will connect and query the database. It will display the result of the query using the print function, which will in turn will be passed by the Javascript code to the HTML container.

<?php

//CONNECT TO MYSQL DATABASE
$con = mysql_connect("localhost", "root", "root1")
or die("<p class='error-msg'>Cannot connect to the database. ".mysql_error()."</p>");

//SELECT A DATABASE
mysql_select_db("test");

//COMPOSE QUERY
$sql = "
SELECT
CONCAT(first_name, ' ', last_name) AS name
FROM employees
LIMIT 0, 10";

//print "<pre>".$sql."</pre>";

//EXECUTE THE QUERY
$result = mysql_query($sql, $con);

while ($row = mysql_fetch_assoc($result))
{
print "<br/>".$row["name"];
}

?>


To run this example, copy and paste the sourcecodes above, name it index.php, ajax.js and ajax.php respectively and save it in the same folder of your server.

0 comments:

Recent Post