Published on 2005-09-25 01:22:13
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.
Member of the PHP Magazine Network, Copyright (C) 2005-2008 phpmagazine.net All Rights Reserved