AJAX earned its share of stardom once industry giants like Google Maps, Zoho Writer and Y!Mail Beta started to actively implement AJAX into their services.
Though many webmasters out there are already using AJAX yet there is that section which is still unaware of its advantages.
This tutorial will help the latter part enjoy hands-on experience with AJAX and PHP. I won’t be using jargons yet I am assuming that you understand the basics of HTML, PHP and JavaScript.
What is AJAX?
Well, AJAX won’t be new for those who understand JavaScript. AJAX stands for Asynchronous JavaScript and XML. Using AJAX programmer can use JavaScript code to get content from server machine without re-loading the complete webpage. Now you know how Google Maps load on the fly without any page re-loads?
Server sends data to client in XML format and client uses JavaScript to parse XML in order to perform the designated task. AJAX can be seamlessly integrated with PHP, Python, ASP (.NET), JSP and almost every other server-side technology.
What is our goal?
We will create a small Availability Checker application for a restaurant. User will enter the number of customers and the application will return if a table is available for that much number of customers. Breaking down Availability Checker:
- index.php will be responsible for displaying a field which consumes data from user and send the same to our business logic for processing.
- myAJAX.php will receive data from index.php and process the same.
- If the input number is within the availability range then we return “Table Available!” otherwise we return “We are full!” as output.
- Lastly, please be aware that we won’t be processing XML anywhere throughout our code. We will dissect the usage of XML in some other tutorial.
Starting with index.html (instead of index.php)
<html>
<head>
<title>First ever Ajax application with PHP</title>
</head>
<body>
<form name="ajaxform" method="get" action="#">
Table for <input type="text" name="number" id="number" value="" />?<br /><br />
<input type="submit" value=" Available? " />
</form>
</body>
</html>
Above code displays an empty text field with a submit button. Please note that I have left the action attribute blank for now.
Moving on to myAJAX.php
<?php
session_start(); // for starting a session
header("Content-type: text/plain");
// Setting HTTP header for plain text
$numbers= array( // this will be our list
'1',
'2',
'3',
'4'
);
if (in_array($_GET['number'], $numbers)) { // if condition satisfied
echo '1'; // results in true
}
else { // otherwise
echo '0'; // results in false
}
?>
myAJAX.php compares the input against a given set of numbers.
- If the input numeral matches with any hardcoded number then it returns 1.
- Otherwise, it returns 0.
The JavaScript!
<script language="JavaScript" type="text/javascript">
<!--
var ajaxVariable = false; // the variable which will make AJAX a possibility for our tutorial
function ajaxFunction(url) {
ajaxVariable = false;
try{
// For latest web browsers like Chrome, Firefox, Safari
ajaxVariable = new XMLHttpRequest();
} catch (e){
// In case of Internet Explorer 6 there are two ways of calling the object
try{
ajaxVariable = new ActiveXObject("Msxml2.XMLHTTP"); // the usual way
} catch (e) {
try{
ajaxVariable = new ActiveXObject("Microsoft.XMLHTTP"); // creating ActiveX controls which will use older XML library
} catch (e){
// When no browser works
alert("Get a working web browser, please!");
return false;
}
}
}
ajaxVariable.onreadystatechange = ajaxReply; // whenever the ready state is changed
ajaxVariable.open('GET', url, true); // opens a request to server
ajaxVariable.send(null); // closes the request
// Now, the code waits unless the ready state changes.
// After every change ajaxReply() is executed
return true;
} // end function ajaxFunction
function ajaxReply() { // your code's logic goes here
if (ajaxVariable.readyState == 4) { // 4 mean page loaded successfully
if (ajaxVariable.status == 200) { // 200 mean all is OK
if (ajaxVariable.responseText == '1') { // if the entry was in our range (1-4)
alert('Table available!');
}
else { // otherwise
alert('We are full!');
}
} // end if
else { // if the status code is anything else (a rare case though)
alert('Something weird occurred. HTTP error code ' + ajaxVariable.status.toString() + '.');
return; // exit
}
} // end if
} // end function ajaxReply
//-->
</script>
AJAX must be initialized before being used in any part of the code. In case of latest browsers a built-in object called XMLHttpRequest is enough while for older versions, we require ActiveX control to perform the same. Although, initializing AJAX isn’t rocket science yet we won’t be discussing the same here. Another day, maybe!
After initializing ajaxVariable (from line 3 to line 25), the code checks for change in ready state of ajaxVariable. A change in ready state means a reply was received from server which kick starts the actual business logic (from line 49 to line 68).
It is time to append the above JavaScript code in your index.html (and rename index.html to index.php just to follow the convention). Remember that JavaScript goes above the <head> tag. Lastly, a minor change in <form> tag will be required so that myAJAX.php is called once the submit button is clicked.