« NAJAX 0.4.1.0 released | Main | Better Web Apps With Ajax »

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.

AJAX Forms

for example if we have a registration form and we want to add a remote validation for the username




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();

AJAX Forms 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.

Download the AJAX Form sample

Bookmark this article at these sites
Comments
1

works fine with FireFox...but has problem with IE
is not getting updated...can anybody tell me y is it so

2

I use firefox only, I'll try fix it for IE also. Thank you

3

Did you find a solution for MSIE?
I tried the result of several ajax-form tutorials on the internet en all of them seem to have problems with MSIE or Opera.
Only one did not and that was a very big one with big frameworks.
Now I'm willing to study that one, but I can't find it again.

So if your simple example works well, I would like to know.

4

this ajax form has some problem on IE in AJAXForms.send(null); line
Has anyone found a roundabout to this? This is a critical line as it informs of the end of xml data which has been returned. Waiting for solution to this problem

5

//try this...it works for me for IE

function CheckField(field) {

var theQuery = "username&field="+field.name+"&value="+field.value;

if(theQuery !== "") {

document.getElementById('result').innerHTML = "Searching...";

var url = "check.php?p="+theQuery;

xmlhttp.open("GET", url, true);

xmlhttp.onreadystatechange = function processChange() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {

document.getElementById('result').innerHTML = xmlhttp.responseText + ' ';
document.getElementById('result').style.visibility = "visible";
}

}; xmlhttp.send(null);
}
}

6

Sorry. This didnt work.

Also looking for a safari mac version

7

I'm also looking for the solution to this problem. I want to use it on my site, but the IE problem could hold me up...That stinks.

Graham - Webmaster

8

Forget this exmaple... worthless :)

9

The problem is as follows:

The input name and div id are the same. So at the end the browser (IE) doesn't know where to put the result.

I alterd the CheckField function to this so the right ActiveXObject is loaded:

[code]
function CheckField(field) {

try
{
AJAXForms = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (error)
{
try
{
if (window.XMLHttpRequest) {
AJAXForms = new XMLHttpRequest();
}
}
catch (error)
{
return false;
}
}
AJAXForms.onreadystatechange = processChange;
AJAXForms.open("GET", "user-check.php?op=ajax&field=response&value=" + field.value);
LastField = "response";
AJAXForms.send(null);
}
[/code]

just rename you div id from username to response and it will work in IE to.

10

Thanks for the IE fix. Seems i cant (yet have two of these objects in the same page. Ive managed to automate most of this using PHP functions and i must say the whole thing is a treat when its working....


FYI for those of you wanting to use the value="something" to generalize this code in a PHP get (i have one file called ajaxquery.php that all ajax queries go to, then i do a

if (($_GET['op'] == 'ajax') && ($_GET['query'] == 'specific_item'))
{
print "your ajax request succeeded!";
}


change the line
AJAXForms.open
to read:

AJAXForms.open("GET", "/include/ajaxquery.php?op=ajax&field=response&value=" + field.value + "&query=" + field.name);

Of course ALWAYS clean your GET's. My code for the IF statement is different, but i kept it the same as the above samples for simplicities sake.

I would imagine if i use something other than

LastField = "response";

i cant generalize this to allow multiple objects per page....

Thanks for posting answers people!

11

Change LastField to read

LastField = "response" +field.name;

and then on your DIV change the ID to read
response[value]

where [value] is the value= from your input object that calls the OnChange="CheckField(this)"


Hope this helps someone!

12

this should fix the IE issues:

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(browser=="Microsoft Internet Explorer"){
object=new ActiveXObject("Microsoft.XMLHTTP");
}else{
object=new XMLHttpRequest();
}
if(!object) alert("There was a problem making an Ajax Connection");
}

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";

}
}

13

Anyone knows how to make a button|link to create an input inside a form already charged.

I found one script to do this but i can't make it work.

Ty.

14

I found neither fix worked very well I have a solution you can use for multiple fields as well.
Your form should look like add::
[CODE] di="ipab" [/CODE]div id="ipab"
change the ipba to whatever you want(other than the "name" value) just make sure you change the DIV ID as well.

Now the AJAX Code ::
[CODE]
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) {

try
{
AJAXForms = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (error)
{
try
{
if (window.XMLHttpRequest) {
AJAXForms = new XMLHttpRequest();
}
}
catch (error)
{
return false;
}
}
AJAXForms.onreadystatechange = processChange;
AJAXForms.open("GET", "check.php?op=ajax&field=" + field.di + "&value=" + field.value + "&name=" + field.name);
LastField = field.di;
AJAXForms.send(null);
}


function processChange() {
if (AJAXForms.readyState == 4) {

var res = document.getElementById(LastField);
res.innerHTML = AJAXForms.responseText;
res.style.visibility = "visible";

}
}

[/CODE]
This will keep it dynamic to your form.

Hope this helps -- Matt

15

Hello !

with me it shows an error with line 45 and always stands there that in it
res.style.visibility = "visible";

sorry for my bad english

16

that is valid opera IE firefox

var AJAXForms;
var LastField = null;
var isIE = (navigator.appName == 'Microsoft Internet Explorer');

function CheckField(field) {
try {
AJAXForms = new XMLHttpRequest();
}catch(e){
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) {
document.getElementById(''+LastField+'_1').innerHTML = AJAXForms.responseText;
document.getElementById(''+LastField+'_1').style.visibility = "visible";

}
}

have fun ;)

17
18

thanks

19

Sooooo much hassle. If your web application depends on intensive forms processing, you'd better consider using a good tool for it.
See how Tigermouse Ajax framework for PHP generates, processes and validates form data whithout writing ANY javascript by hand. Goto http://tigermouse.epsi.pl for further information or email me directly.

20

The problem with this code is that IE does not support innerhtml in this circumstance....unless you change your landing tag to a

    which is just silly.

Post a comment





(Email will remain hidden)





Please enter the security code you see here




Related entries
Email to a friend
Email this article to:


Your email address:


Message (optional):