Monday Oct 20
Nov
30/12
jQuery AJAX Validation for Existing DB Entries
Last Updated on Wednesday, 14 May 2014 09:59
Written by Cody Snider
Friday, 30 November 2012 02:48

These are the basic steps for using an AJAX request to check if a username or email address (or any field that must be unique in the database) already exists. For this example we’ll be using the jQuery Validation Plugin.

First, let’s look at the template for the server-side code. We’ll use PHP for this example, but the Javascript doesn’t care what language as used so long as the response is a JSON encoded true or false. Handling this in PHP is very easy to both build and read.

Before using the PHP code below, there are some things you should be aware of. First, this is running a raw request parameter into your database. This is a big security risk (SQL injection attacks) and you will need to sanitize the data before using it in a query. Depending on the framework or ORM you are using, this may be handled for you, but please check before implementing this code. Another security concern is cross-site request forgery (CSRF). This is where another site or a bot will blast your ajax URL to try to submit data outside the context of your forms. This is used to expose things like registered email addresses or to make false registrations altogether. Both these security concerns are beyond the scope of this article, but something to be aware of.

<?php
 
if($_REQUEST('email_address')) {
 
    $result = mysql_query("SELECT * FROM `users` WHERE `email_address` = '" . $_REQUEST['email_address'] . "' LIMIT 1;");
    if(mysql_num_rows($result) === 1) {
        echo json_encode(true);
    } else {
        echo json_encode(false);
    }
} else {
    echo json_encode(false);
}
 
?>

Next, we’ll add the Javascript code. We’re testing an email address in this example, so we’ll likely have this element somewhere on the page:

<form id="signup_form">
    <input type="text" name="email_address" id="email_address" />
</form>

Because we don’t want to blast the server with a request every time a button is pressed, we’ll use the native setTimeout function in Javascript to provide a 1.5 second delay. The function that is fired when the delay completes and runs the callback is going to validate just the one field we’re working with and none of the others (everything else, including this, will run on submit).

View Code JAVASCRIPT
var check_email_timeout;
jQuery(function($){
    $('#email_address').bind('keypress change', function(e) {
        clearTimeout(check_email_timeout);
        check_email_timeout = setTimeout(function(){
            $('#signup_form').validate().element($('#email_address'));
        }, 1500);
    });
});

First, we declare the check_email_timeout so that our clearTimeout has something defined to work with on first pass (though it will do nothing at this point). Next, we’re setting the keyup and change events on the email_address element to both fire the anonymous function that handles the validation. The timeout function is set to run yet another anonymous function that executes the validation of the email address element.

Now, let’s look at the rule we’ll need to set for this to work.

View Code JAVASCRIPT
$('#signup_form').validate({
    rules: {
        email_address: {
            required: true,
            email: true,
            remote: '/your_script.php' + $('#email_address').val()
        },
    },
    messages: {
        email_address: {
            required: 'Please enter an email address',
            remote: 'Email address is already registered',
            email: 'Invalid email address'
        }
    }
});

So long as the validation plugin is available, this will attach the required validation to handle the remote lookup.

The validation plugin has a ton of options and is easy to extend. I’d recommend reading further into the options available on the jQuery documentation linked to in the first paragraph of this article.

Cheers and let me know if you find any bugs or have any improvements that should be added.



Leave a Reply






Buy me a beer

What better way to say you love the article than a cold, refreshing beer? Cheers. :-)

    • Software engineer from NYC proficient in PHP, Python, HTML, CSS, Javascript and AS3.