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

26 Comments on "Create AJAX form with PHP"

  1. Riax November 17, 2005 at 5:49 am · Reply

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

  2. Hatem November 17, 2005 at 6:58 am · Reply

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

  3. Anko December 8, 2005 at 9:55 am · Reply

    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. nikhil February 2, 2006 at 7:47 am · Reply

    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. paul February 20, 2006 at 12:56 pm · Reply

    //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. roberto March 21, 2006 at 9:55 pm · Reply

    Sorry. This didnt work.
    Also looking for a safari mac version

  7. Wrapsacks June 3, 2006 at 5:06 am · Reply

    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. oliver July 11, 2006 at 7:17 pm · Reply

    Forget this exmaple… worthless :)

  9. Sander July 27, 2006 at 12:22 pm · Reply

    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. Crudster August 27, 2006 at 7:31 am · Reply

    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. Crudster August 27, 2006 at 7:41 am · Reply

    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. Jonathan January 11, 2007 at 9:20 pm · Reply

    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. esteban January 23, 2007 at 10:06 pm · Reply

    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. Matt January 24, 2007 at 6:27 am · Reply

    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. rompers February 7, 2007 at 8:38 pm · Reply

    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. clamsy February 8, 2007 at 9:53 am · Reply

    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. hiro February 22, 2007 at 3:36 pm · Reply

    XMLHttpRequest for IE
    http://la.ma.la/misc/js/ie_xmlhttp.html

  18. haidar June 5, 2007 at 2:02 am · Reply

    thanks

  19. Michal Slaby July 30, 2007 at 7:57 pm · Reply

    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. Steve November 18, 2007 at 2:25 am · Reply

    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.

  21. Ani April 15, 2009 at 9:21 am · Reply

    Please guide me to generate a AJAX code which will return more than one values and the returned values should be displayed in a multiline textbox

  22. madeinara July 2, 2009 at 9:44 am · Reply

    why the submit button cannot be responding??
    and call some file in ajax??

  23. tim September 6, 2009 at 4:14 pm · Reply

    heres a good one: Its a login script and it has ajax jquery for validating the registration form : http://tympanus.net/codrops/2009/09/03/php-login-system-reloaded/

  24. david December 5, 2009 at 5:57 pm · Reply

    here’s another very good one, it is very useful for my AJAX apps , I hope it would help http://phpstring.co.cc/phpclasses/modules/ajax-registration-module/register/

  25. Project Management Software June 4, 2010 at 9:58 am · Reply

    heres a good one: Its a login script and it has ajax jquery for validating the registration form : http://tympanus.net/codrops/2009/09/03/php-login-system-reloaded/

  26. sohbet November 25, 2010 at 10:54 pm · Reply

    Thank you for blogging this, it was quite handy and helped a lot

Leave a Comment