Friday, 15 July 2011

Live username validation using jQuery and PHP

index.html
<!DOCTYPE html>
<html>
    <head>
        <title></title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
         <script type="text/javascript"  src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
        <style type="text/css">
            #feedback
            {
                color:green;
                font-weight:bold;
            }
        </style>
    </head>
    <body>
        <input type="text" id="name"/>
        <script type="text/javascript" src="js.js"></script>
        <div id="feedback"></div>
    </body>
</html>

js page

$('#name').keyup(function(){
   var name=$(this).val(); //the name entered by the user is stored in the variable, name

    //Post the variable. 3 variables, 'destination  page',variable_key:value, callback function(which accepts the value  returned from PHP page 
    $.post('process_form.php',{name:name},function(data){
       $('#feedback').html(data);  //the div is modified with the html value reciecved from the PHP page 
    });
   
});
php page
<?php
$name=$_POST['name'];

//Whatever is echoed out will be recieved by the js page and added to the div in the index.html page
if(strlen($name)>7)
        if(strlen($name)>13)
            echo "Cannot be more than 12";
        else
            echo "STRONG";
    else
        echo "Username must be atleast 8 chars";
?>

No comments:

Post a Comment