article

Friday, July 26, 2013

Username availability check using PHP and jQuery

Username availability check using PHP and jQuery
 
<?php

/* CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`username` varchar(150) NOT NULL,
`email` varchar(100) NOT NULL',
`pass` varchar(100)  NOT NULL',
PRIMARY KEY (`id`)
) */
//Username availability check using PHP and jQuery
//if we got something through $_POST
if (isset($_POST['user'])) {
    // here you would normally include some database connection
    include('db.php');
    $db = new db();
    // never trust what user wrote! We must ALWAYS sanitize user input
    $username = mysql_real_escape_string($_POST['user']);
    // build your query to the database
    $sql = "SELECT count(*) as num FROM users WHERE username = " . $username;
    // get results
    $row = $db->select_single($sql);
    if($row['num'] == 0) {
        echo 'Username <em>'.$username.'</em> is available!';
    } else {
        echo 'Username <em>'.$username.'</em> is already taken!';
    }
}
?>
<script>
$(function() {
$("#sub").click(function() {
    // getting the value that user typed
    var checkString    = $("#username_box").val();
    // forming the queryString
    var data            = 'user='+ checkString;
 
    // if checkString is not empty
    if(checkString) {
        // ajax call
        $.ajax({
            type: "POST",
            url: "do_check.php",
            data: data,
            beforeSend: function(html) { // this happen before actual call
                $("#results").html('');
            },
            success: function(html){ // this happen after we get result
                $("#results").show();
                $("#results").append(html);
            }
        });
}
return false;
});
});
</script>
<form action="do_check.php" method="post">
    <input id="username_box" class="search_box" name="username" type="text" />
    <input id="sub" type="submit" value="Check" />
</form>

Related Post