Posted on April 9, 2008 by Elliott Brueggeman15 Comments »

Background

Previously I posted my PHP AJAX Framework so I thought I would give an example of its use. In this case, you probably have seen this example before – using AJAX and PHP to check if a username is available during some kind of web-based user registration. The goal is to alert the user if a username is taken before they have submitted the form, allowing them to enter another username quickly. This feat can be easily accomplished with the PHP AJAX Framework.

Setup

You are going to need to copy the contents of the PHP AJAX Framework into a JavaScript file. In this example I have put the contents into the “php_ajax_framework.js” file. You are also going to need to write a PHP script that will be called in the AJAX sequence of events, notifying the user whether the username is available or not.

Below is an example PHP Script, which has the filename “username_exists.php” and will need to be in the same directory as the page that is triggering the AJAX.

PHP Username Available Script

This script is requested by our AJAX helper function and sent the text in our username input box. In the script is a call to a function usernameExists() which returns true or false, depending on whether the username exists. In a real web site or application, this would query our database to see if the username existed. In this example, for ease of understanding, we just check to see if the username is in a defined array of usernames.

<?php 
$username = trim($_GET['username']);
 
if (usernameExists($username)) {
  echo '<span style="color:red";>Username Taken</span>';
}
else {
  echo '<span style="color:green;">Username Available</span>';
}
 
function usernameExists($input) {
  // in production use we would look up the username in 
  // our database, but for this example, we'll just check
  // to see if its in an array of preset usernames.
  $name_array =  array ('steve', 'jon', 'george', 'admin');
 
  if (in_array($input, $name_array)) {
    return true;
  }
  else {
    return false;
  }
}
?>

Username Check Page

Our example username page is very basic – you should integrate this into your existing site. The important parts are the JavaScript functions and the input box, which uses the onKeyUp() JavaScript event to call a function which them triggers the AJAX chain of events. More information on setting up the PHP AJAX Framework can be found on its post page, but the basic idea is that you create an _init function that specifies which PHP script to execute and what variables to send it (in this case, the value of the user input box.) You also create a _results function which will be given the results of your PHP Script and then do something with them (in this case, display a notice to the user whether the name is available.) The _init and _results functions are given function names prepended to these terms which are the same (in the below case, we prepend “check_username” to both) and then they are triggered by calling our PHP AJAX Framework function ajaxHelper() with the name we prepended.

<html>
<head>
<script type="text/javascript" src="php_ajax_framework.js"></script>
<script type="text/javascript">
function check_username_init() {
  var user_field = document.getElementById('user');
  return 'username_exists.php?username=' + user_field.value;
}
function check_username_ajax(results) {
  var results_div = document.getElementById('results_div');
  results_div.innerHTML = results;
}
function check_username() {
  var user_field = document.getElementById('user');
  if (user_field.value.length > 0) {
    //call our AJAX function in the PHP AJAX Framework
    ajaxHelper('check_username');
  }
  else {
    //clear results field 
    var results_div = document.getElementById('results_div');
    results_div.innerHTML = '';
  }
}
</script>
</head>
<body>
Username: 
<input name="user" id="user" size="20" onKeyUp="check_username();">
<div id="results_div"></div>
</body>
</html>

Here is an live example of the above scripts all working together. Remember that we are just checking against an array of names. Try typing in one of the names in the array to see what happens when a particular username is taken (steve, jon, george, admin.)

Conclusion

Implementing AJAX is easy and just requires putting all the pieces together. Give AJAX and shot and implement the PHP AJAX Framework on your site for simple AJAX tasks.

Comments

  1. Greg on 07 Nov 2008 at 3:36 pm

    What a great yet simple explanation…

  2. ashokkumar on 18 Nov 2008 at 2:57 am

    what a simple explanation!! i really enjoyed it..
    you great..

  3. jeric on 10 Feb 2009 at 7:52 pm

    I’m just a newbee in ajax, this is a very good tutorial. keep up the good work!

  4. nd on 25 Mar 2009 at 5:12 pm

    nice work

  5. Gildo on 28 Apr 2009 at 5:29 am

    Hi,

    I tried to modify the php code to get the user from a db:

    <?php
    include (”includes/connection.php”);

    $username = trim($_GET['username']);
    if (usernameExists($username))
    echo ‘Username already in use!’;
    else
    echo ‘Username Available’;

    function usernameExists($input)
    {
    $count = mysql_num_rows(mysql_query(”SELECT * FROM `users` WHERE `username`=’”.$input.”‘”));

    if($count > 0)
    return true;
    else
    return false;
    }
    ?>

    I just modified this only but I keep on getting this Javascript error:

    Error: unterminated string literal
    Source File: http://www.doyouregret.com/js/php_ajax_framework.js
    Line: 39, Column: 20
    Source Code:
    check_username_ajax(’Username Available

    If I use the exact php code you posted above it works so it’s not a matter of html or wrong php_ajax_framework.js.

    Can you help me?

    Thanks,
    Gildo

  6. Elliott Brueggeman on 28 Apr 2009 at 5:43 am

    You need to change the check_username_ajax(’Username Available’) line. You should have a variable there so that when the hook calls that function, it can pass the value of the results in for use. Note in the example I use the variable results.

  7. Gildo on 28 Apr 2009 at 5:48 am

    Do you mean this line:

    function check_username_ajax(results) {
    var results_div = document.getElementById(’results_div’);
    results_div.innerHTML = results;
    }

  8. Elliott Brueggeman on 28 Apr 2009 at 6:15 am

    Yes – from your error though, it looks like you are substituting a literal string where there should be a variable.

  9. Gildo on 28 Apr 2009 at 6:26 am

    I didn’t substitute anything, I just changes those lines in the php script:

    function usernameExists($input) {
    // in production use we would look up the username in
    // our database, but for this example, we’ll just check
    // to see if its in an array of preset usernames.
    $name_array = array (’steve’, ‘jon’, ‘george’, ‘admin’);

    if (in_array($input, $name_array)) {
    return true;
    }
    else {
    return false;
    }

    with those:

    function usernameExists($input)
    {
    $count = mysql_num_rows(mysql_query(”SELECT * FROM `users` WHERE `username`=’”.$input.”‘”));

    if($count > 0)
    return true;
    else
    return false;
    }

    where am I wrong? The function usernameExists return true or false as with your code, please advice, I’m stuck!

  10. Elliott Brueggeman on 28 Apr 2009 at 6:33 am

    Well assuming you have identical javascript code too, I would say that an MYSQL error is breaking the code. Have you successfully connected to the database? http://us2.php.net/manual/en/mysql.examples-basic.php

  11. Gildo on 28 Apr 2009 at 6:38 am

    Yes, If I run the script username_exists.php directly from the browser like this:

    http://www.doyouregret.com/ajax_test/username_exists.php?username=pippo

    the script works! So I’m really stuck. When you have some spare time can you please try it on a database please?

    Thanks,
    Gildo

  12. Elliott Brueggeman on 28 Apr 2009 at 6:44 am

    well to replicate the database situation, I’d have to have your exact database. Echo the results of the mysl query and run the ajax php script itself to make sure you are getting expected results. Then, double check that that function is echoing out “username taken”, etc. Just take it apart one step at a time.

  13. Gildo on 28 Apr 2009 at 6:46 am

    I did it, the problem lies in the php script. As soon as I use your code it works like a charm, when I add the database connection code I get the javascript error. The script works as I told you in my previous comment. You can try at:

    http://www.doyouregret.com/signup.php

    the first field username triggers the javascript error (I see it with the firefox error console).

  14. Gildo on 28 Apr 2009 at 9:14 am

    Ok, never mind. It’s working now and I don’t know the reason yet…

  15. Felix (FIN) on 06 Jul 2010 at 6:07 am

    Very simple and yet extremely resuable code! Thanks!!!

Leave a Reply - Registration Not Necessary