Create AJAX form with PHP
I have received many message and emails asking about easy solution to create forms with AJAX. Someone new to AJAX or Javascript who saw the available frameworks will just give up, while it's very easy to implement without all this complexity. So this is a fast way to create AJAX forms and I'll introduce later a framework wich will automate forms processing.
for example if we have a registration form and we want to add a remote validation for the username
I have used the OnChange event so the remote request will be done only if the username enter a value. This username will be checked if it's available or no on the database. The Javascript used is the following :
/**
* AJAX forms
*
* Author : Hatem B.Y.
*/
var AJAXForms = false;
var LastField = null;
var isIE = false;
// on !IE we only have to initialize it once
if (window.XMLHttpRequest) {
AJAXForms = new XMLHttpRequest();
}
function CheckField(field) {
if (window.XMLHttpRequest) {
// branch for IE/Windows ActiveX version
} else if (window.ActiveXObject) {
AJAXForms = new ActiveXObject("Microsoft.XMLHTTP");
}
AJAXForms.onreadystatechange = processChange;
AJAXForms.open("GET", "check.php?op=ajax&field=" +field.name+"&value=" + field.value);
LastField = field.name;
AJAXForms.send(null);
}
function processChange() {
if (AJAXForms.readyState == 4) {
var res = document.getElementById(LastField);
res.innerHTML = AJAXForms.responseText;
res.style.visibility = "visible";
}
}
Once we finished requesting data from server, the php script will just check if the username typed is available or no. I used mysql db in this example :
if ($_GET['op'] == 'ajax') {
$link = mysql_connect("localhost", "root", "");
mysql_select_db("ajax");
$query = "SELECT id FROM users where username='".mysql_escape_string($_GET['value'])."'";
$result = mysql_query($query);
$num_rows = mysql_num_rows($result);
if ($num_rows == 0) {
$msg = 'available';
$class = "green";
} else {
$msg = 'Not Available';
$class = "red";
}
}
echo "
$msg";
die();
With the addition of some stylesheet you can see the result of this code. The framework can generate forms more easily, and I have written the Javascript in the way it could be used with many fields in the same form. For example if we want to add a checkbox to suggest other usernames.


Subscribe to AJAX Magazine's feed