PHP is an amazing web programming language, and it does wonders when you add AJAX to spice up your application. So in this dirty tutorial, I will share with you how to make a standard HTML form, but let PHP handle it without actually refreshing the HTML page or even submitting the web page to another flat PHP file.
Requirements
To get the most out of this tutorial, I recommend get Dreamweaver from www.adobe.com, and download the AJAX framework for PHP, XAJAX 0.5. And also you need to have a very sharp brain to understand the concept in a timely manner ;).
- Dreamweaver
- XAJAX
The Skeleton
Everytime you do something complex it's a good idea to plan ahead. Because you will know what type of problems could lie ahead and will have an idea on how to solve those problems. As for this small application goes, it will work like the diagram below:

According to the diagram above you probably know by now that the user will be presented with the HTML Form. Then via AJAX, the data of the form will be sent to the PHP File. And then PHP file will manipulate those data and send them back to the HTML page through the port opened by AJAX. And all this things will happen without any page refresh or redirect. Got it? Good!
The HTML Page
I assume you are a guru in HTML or at least experienced with it. So I won't bother going over the HTML form in detail. Our HTML Form looks like this:

And the source of the above XHTML page is below.
- <?php require('init.php'); ?>
- <!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">
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
- <title>Simple HTML Form</title>
- <style type="text/css">
- <!--
- body,td,th {
- font-family: Arial, Helvetica, sans-serif;
- font-size: 12px;
- color: #000000;
- }
- a:link {
- color: #000099;
- text-decoration: none;
- }
- a:visited {
- text-decoration: none;
- color: #000099;
- }
- a:hover {
- text-decoration: underline;
- background-color:#FFFF00;
- color: #990000;
- }
- a:active {
- text-decoration: none;
- color: #000099;
- }
- .wrapper {
- border: thin groove #CCCCCC;
- padding: 5px;
- width: 700px;
- }
- input {
- border: 1px solid #ABADB3;
- background-color: #FFFFFF;
- padding: 2px;
- }
- .lblCol {
- font-weight: bold;
- color: #990000;
- }
- -->
- </style>
- <?php $xajax->printJavascript('xajax'); ?>
- <script type="text/javascript" language="javascript">
- function submitForm()
- {
- xajax.$('submit').disabled=true;
- xajax.$('submit').value="Please wait...";
- xajax_processForm(xajax.getFormValues("jobApplicationForm"));
- return false;
- }
- </script>
- </head><P></P>
- <P><body>
- <table width="100%" border="0" class="wrapper" align="center">
- <tr>
- <td>
- <div id="formBox">
- <h2>Job Application</h2>
- <hr />
- <form action="javascript:void(null);" method="post" enctype="application/x-www-form-urlencoded" name="jobApplicationForm" id="jobApplicationForm">
- <table width="100%" border="0" cellspacing="6" cellpadding="5">
- <tr>
- <td width="16%" class="lblCol">First Name:</td>
- <td width="84%"><input type="text" name="firstName" id="firstName" onblur="xajax_checkField(this.value, 'firstNameLbl')" /><label id='firstNameLbl'></label></td>
- </tr>
- <tr>
- <td class="lblCol">Last Name:</td>
- <td><input type="text" name="lastName" id="lastName" onblur="xajax_checkField(this.value, 'lastNameLbl')" /><label id='lastNameLbl'></label></td>
- </tr>
- <tr>
- <td class="lblCol">Email Address:</td>
- <td><input type="text" name="emailAddress" id="emailAddress" onblur="xajax_checkField(this.value, 'emailAddressLbl')" /><label id='emailAddressLbl'></label></td>
- </tr>
- <tr>
- <td class="lblCol">Age:</td>
- <td><input name="age" type="text" id="age" onblur="xajax_checkField(this.value, 'ageLbl')" size="5" />
- <label id='ageLbl'></label></td>
- </tr>
- <tr>
- <td class="lblCol">Languages:</td>
- <td><input type="checkbox" name="languagesPHP" id="checkbox" value="PHP" /> PHP<br />
- <input type="checkbox" name="languagesASP" id="checkbox" value="ASP" /> ASP<br />
- <input type="checkbox" name="languagesRuby" id="checkbox" value="Ruby" /> Ruby<br /></td>
- </tr>
- <tr>
- <td class="lblCol">Nationality:</td>
- <td><select name="nationality" onchange="xajax_checkField(this.value, 'nationalityLabel')">
- <option>Please Choose Nationality</option>
- <option value="usa">American</option>
- <option value="english">British</option>
- <option value="bd">Bangladeshi</option>
- </select>
- <label id="nationalityLabel"></label></td>
- </tr>
- <tr>
- <td colspan="2">
- <div id="notifier" align="center" style="display:block">
- <input type="submit" name="submit" id="submit" value="Submit Application" onclick="submitForm()" />
- </div>
- </td>
- </tr>
- </table>
- </form>
- </div>
- </td>
- </tr>
- </table>
- </body>
- </html>
- </P>
<?php require('init.php'); ?>
<!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">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Simple HTML Form</title>
<style type="text/css">
<!--
body,td,th {
font-family: Arial, Helvetica, sans-serif;
font-size: 12px;
color: #000000;
}
a:link {
color: #000099;
text-decoration: none;
}
a:visited {
text-decoration: none;
color: #000099;
}
a:hover {
text-decoration: underline;
background-color:#FFFF00;
color: #990000;
}
a:active {
text-decoration: none;
color: #000099;
}
.wrapper {
border: thin groove #CCCCCC;
padding: 5px;
width: 700px;
}
input {
border: 1px solid #ABADB3;
background-color: #FFFFFF;
padding: 2px;
}
.lblCol {
font-weight: bold;
color: #990000;
}
-->
</style>
<?php $xajax->printJavascript('xajax'); ?>
<script type="text/javascript" language="javascript">
function submitForm()
{
xajax.$('submit').disabled=true;
xajax.$('submit').value="Please wait...";
xajax_processForm(xajax.getFormValues("jobApplicationForm"));
return false;
}
</script>
</head>
<body>
<table width="100%" border="0" class="wrapper" align="center">
<tr>
<td>
<div id="formBox">
<h2>Job Application</h2>
<hr />
<form action="javascript:void(null);" method="post" enctype="application/x-www-form-urlencoded" name="jobApplicationForm" id="jobApplicationForm">
<table width="100%" border="0" cellspacing="6" cellpadding="5">
<tr>
<td width="16%" class="lblCol">First Name:</td>
<td width="84%"><input type="text" name="firstName" id="firstName" onblur="xajax_checkField(this.value, 'firstNameLbl')" /><label id='firstNameLbl'></label></td>
</tr>
<tr>
<td class="lblCol">Last Name:</td>
<td><input type="text" name="lastName" id="lastName" onblur="xajax_checkField(this.value, 'lastNameLbl')" /><label id='lastNameLbl'></label></td>
</tr>
<tr>
<td class="lblCol">Email Address:</td>
<td><input type="text" name="emailAddress" id="emailAddress" onblur="xajax_checkField(this.value, 'emailAddressLbl')" /><label id='emailAddressLbl'></label></td>
</tr>
<tr>
<td class="lblCol">Age:</td>
<td><input name="age" type="text" id="age" onblur="xajax_checkField(this.value, 'ageLbl')" size="5" />
<label id='ageLbl'></label></td>
</tr>
<tr>
<td class="lblCol">Languages:</td>
<td><input type="checkbox" name="languagesPHP" id="checkbox" value="PHP" /> PHP<br />
<input type="checkbox" name="languagesASP" id="checkbox" value="ASP" /> ASP<br />
<input type="checkbox" name="languagesRuby" id="checkbox" value="Ruby" /> Ruby<br /></td>
</tr>
<tr>
<td class="lblCol">Nationality:</td>
<td><select name="nationality" onchange="xajax_checkField(this.value, 'nationalityLabel')">
<option>Please Choose Nationality</option>
<option value="usa">American</option>
<option value="english">British</option>
<option value="bd">Bangladeshi</option>
</select>
<label id="nationalityLabel"></label></td>
</tr>
<tr>
<td colspan="2">
<div id="notifier" align="center" style="display:block">
<input type="submit" name="submit" id="submit" value="Submit Application" onclick="submitForm()" />
</div>
</td>
</tr>
</table>
</form>
</div>
</td>
</tr>
</table>
</body>
</html>
Most likely you will recognize the codes above. But I will go over some of the codes which you need to be familiar with.
The first code you see on the top of the page:
- require('init.php');
require('init.php');
Is basically including the PHP file which will handle the whole form :).
Next the code just before the </head> tag:
- $xajax->printJavascript('xajax');
$xajax->printJavascript('xajax');
Is nothing but a method from XAJAX class, which prints out the necessary Javascript code needed for the AJAX form to work.
Immediately after the PHP code, you will see a little Javascript like below:
- <script type="text/javascript" language="javascript">
- function submitForm()
- {
- xajax.$('submit').disabled=true;
- xajax.$('submit').value="Please wait...";
- xajax_processForm(xajax.getFormValues("jobApplicationForm"));
- return false;
- }
- </script>
<script type="text/javascript" language="javascript">
function submitForm()
{
xajax.$('submit').disabled=true;
xajax.$('submit').value="Please wait...";
xajax_processForm(xajax.getFormValues("jobApplicationForm"));
return false;
}
</script>
The Javascript codes above is called when the user submits the Submit Application button. The first thing it does is disable the Submit Application button, and replaces it with the text Please Wait... to let the user know that the form has been submitted and it is doing work. Next via AJAX the function calls the PHP function processForm(), and passes the arguments of the form :).
Then, you will notice I've set the form action to javascript:void(null);. This tiny little code means do not submit the form to any webpage. Since we will be using AJAX to communicate with the PHP file, it will be a waste of time to submit the form to another webpage.
After this you probably gonna wonder about the code like below:
- <input type="text" name="firstName" id="firstName" onblur="xajax_checkField(this.value, 'firstNameLbl')" /><label id='firstNameLbl'></label>
<input type="text" name="firstName" id="firstName" onblur="xajax_checkField(this.value, 'firstNameLbl')" /><label id='firstNameLbl'></label>
The onblur event in the input field is mainly saying when the user moves away from this field to another, call the function called xajax_checkField();. So when javascript do call this function xajax_checkField(), AJAX will call checkField() PHP function from the init.php file :). Got it? If not read again! The function checkField() takes in two arguements, one is the value of the field and the other is the id of the label.
So when the user types some contents in the text field, the label will be updated telling the user that the field is filled. But if it is empty, the label will display an error message of sort :).
Finally the Submit Application button has an onclick attribute. This means, when the user clicks this button, the form will be processed by the javascript function submitForm(), which will later call the PHP function processForm().
The PHP File
To save some time, and to make things easier for you I chose not to write the init.php file step by step. Because honestly it is a complete waste of time since most things are repetition of the main idea and bores the hell out of the readers. The source codes of init.php file is:
- <?php
- require ('xajax/xajax_core/xajax.inc.php');
- function checkField($fieldContents, $label)
- {
- $objResponse = new xajaxResponse();
- if(emptyempty($fieldContents))
- {
- $objResponse->assign("sessionBox", "innerHTML", "Numbers of Errors: ".$_SESSION['formErrors']);
- $objResponse->assign($label, "innerHTML", " <font color='red'>Please fill me out!</font>");
- }
- else
- {
- $objResponse->assign($label, "innerHTML", " <font color='green'>Ok</font>");
- }
- return $objResponse;
- }
- function processForm($data)
- {
- $objResponse = new xajaxResponse();
- $firstName = $data['firstName'];
- $lastName = $data['lastName'];
- $emailAddress = $data['emailAddress'];
- $age = $data['age'];
- $languagesPHP = $data['languagesPHP'];
- $languagesASP = $data['languagesASP'];
- $languagesRuby = $data['languagesRuby'];
- if(emptyempty($firstName) && emptyempty($lastName) && emptyempty($emailAddress) && emptyempty($age))
- {
- $objResponse->assign("formBox", "innerHTML", "<font color='red'>Please fill out the form completely.</font>");
- }
- else
- {
- //You may use the data to store them in your database or email
- $sendEmailorDatabaseStoreWasSuccessful = true;
- if($sendEmailorDatabaseStoreWasSuccessful)
- {
- $objResponse->assign("formBox", "innerHTML", "<font color='green'>The form has been successfully sent!</font>");
- }
- }
- return $objResponse;
- }
- $xajax = new xajax();
- //$xajax->bDebug = true;
- $xajax->registerFunction("checkField");
- $xajax->registerFunction("processForm");
- $xajax->processRequest();
- ?>
<?php
require ('xajax/xajax_core/xajax.inc.php');
function checkField($fieldContents, $label)
{
$objResponse = new xajaxResponse();
if(empty($fieldContents))
{
$objResponse->assign("sessionBox", "innerHTML", "Numbers of Errors: ".$_SESSION['formErrors']);
$objResponse->assign($label, "innerHTML", " <font color='red'>Please fill me out!</font>");
}
else
{
$objResponse->assign($label, "innerHTML", " <font color='green'>Ok</font>");
}
return $objResponse;
}
function processForm($data)
{
$objResponse = new xajaxResponse();
$firstName = $data['firstName'];
$lastName = $data['lastName'];
$emailAddress = $data['emailAddress'];
$age = $data['age'];
$languagesPHP = $data['languagesPHP'];
$languagesASP = $data['languagesASP'];
$languagesRuby = $data['languagesRuby'];
if(empty($firstName) && empty($lastName) && empty($emailAddress) && empty($age))
{
$objResponse->assign("formBox", "innerHTML", "<font color='red'>Please fill out the form completely.</font>");
}
else
{
//You may use the data to store them in your database or email
$sendEmailorDatabaseStoreWasSuccessful = true;
if($sendEmailorDatabaseStoreWasSuccessful)
{
$objResponse->assign("formBox", "innerHTML", "<font color='green'>The form has been successfully sent!</font>");
}
}
return $objResponse;
}
$xajax = new xajax();
//$xajax->bDebug = true;
$xajax->registerFunction("checkField");
$xajax->registerFunction("processForm");
$xajax->processRequest();
?>
In the above PHP code the first thing I did is included the XAJAX library. Because without it, implementing AJAX in our application will be bit hard and time consuming.
Next I've created the functions which will be called by XAJAX to check the fields and process the form. Let's explore the checkField() function in detail.
- function checkField($fieldContents, $label)
- {
- $objResponse = new xajaxResponse();
- if(emptyempty($fieldContents))
- {
- $objResponse->assign("sessionBox", "innerHTML", "Numbers of Errors: ".$_SESSION['formErrors']);
- $objResponse->assign($label, "innerHTML", " <FONT color=red>Please fill me out!</FONT>");
- }
- else
- {
- $objResponse->assign($label, "innerHTML", " <FONT color=green>Ok</FONT>");
- }
- return $objResponse;
- }
function checkField($fieldContents, $label)
{
$objResponse = new xajaxResponse();
if(empty($fieldContents))
{
$objResponse->assign("sessionBox", "innerHTML", "Numbers of Errors: ".$_SESSION['formErrors']);
$objResponse->assign($label, "innerHTML", " Please fill me out!");
}
else
{
$objResponse->assign($label, "innerHTML", " Ok");
}
return $objResponse;
}
This function checks the data of a text field and depending on the content, it returns a feedback. The first parameter is the value of the field. And the second parameter is the id of the label in which the feedback will be updated. So for example when the user types his first name in the first name text field, and moves on to the last name field. AJAX will call checkField() function to check first name textfield and will passthe value of the first name field and the id of the first name label. Then checkField() will check and see if the value is empty or not. If it is empty, then the user will get a nice error saying Please fill me out, or else we can assume it is filled, and the user will get the OK message.
Next in the function you need to instantiate the xajaxResponse object in order to return a XML context. Next you tell XAJAX to completely replace the label with some HTML codes. And finally you pass in whatever your HTML code is.
I know this party is bit dodgy, just read again and you will get it :).
Finally almost at the end of the PHP file, I've created an instance of XAJAX. Told it to handle those PHP functions using AJAX and finally ordered it to process all kinds of AJAX requests :).
That's it, you are done!
discuss this topic to forum
