View Full Version : Simple AJAX/PHP Example

Velox Letum
Dec 15th, 2005, 05:09 AM
As I posted this in a topic in normal PHP forum, I thought I'd also post it in here where it can be discussed properly. AJAX is used to add more interactivity to a web page with Javascript and XML using what's known as an XMLHTTP request. This example combines Javascript, PHP, and XML to effectively provide dynamic response to a MySQL query.

This example uses the Sarissa XMLHTTP library, a cross-browser XMLHTTP wrapper which can be downloaded at http://www.sourceforge.net/projects/sarissa.

The HTML/Javascript page (conforms to XHTML 1.0 Transitional standards):

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<title>AJAX Example 1</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<script language='JavaScript' src='sarissa.js' type='text/javascript'></script>
<script language='JavaScript' type='text/javascript'>
function deleterow(id) {

if (confirm('Are you sure you want to delete row number ' + id + '?')) {

// Set up the request
var xmlhttp = new XMLHttpRequest();
xmlhttp.open('POST', 'mycheck.php', true);

// The callback function
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
var response_stat = xmlhttp.responseXML.getElementsByTagName('deleted')[0].firstChild.data;
if (response_stat == 1) {
alert('Deleted row successfully.');
} else {
alert('Failed to delete row: ' + xmlhttp.responseXML.getElementsByTagName('error')[0].firstChild.data + '.');

// Send the POST request
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send('row=' + id);
<input type="button" onclick="deleterow(3);" value="Delete Row" />

The PHP Page:

if (isset($_POST['row'])) {
// Identify as XML
header('Content-type: text/xml');

// MySQL Stuff (connect, select, query)
$result = mysql_query('DELETE FROM row WHERE row="' . $_POST['row'] . '"');

// XML Preamble
$xml = '<?xml version="1.0" encoding="utf-8"?>' . "\n";

// Begin XML response
$xml .= '<xmlresponse>' . "\n";

// Build result string
if ($result) {
$xml .= '<deleted>1</deleted>' . "\n";
} else {
$xml .= '<deleted>0</deleted>' . "\n";
$xml .= '<error>' . mysql_error() . '</error>' . "\n";

// End XML response
$xml .= '</xmlresponse>' . "\n";

// Output XML string
echo $xml;

As you can see, this could be extremely useful in a number of projects. You could dynamically load data into a table, and use XMLHTTP requests to modify it on demand. As long as the browser supports Javascript, the applications for AJAX are virtually limitless.