on Articles Tutorials

jQuery Live Login inspired by Google Instant Search

Tweet about this on TwitterShare on FacebookShare on Google+Share on LinkedInShare on RedditShare on StumbleUpon

We visit thousands of web pages and log in to hundreds of them. Always the same thing is repeating every single time. You enter username, press tab, enter password, press Enter key or click on a button.

I was inspired by Google Instant Search and I will demonstrate how we can build log in functionality without having to press Enter or click a button. This is fairly simple task and using jQuery and a touch of PHP, we can achieve this in no time.

You can see the finished script in action below:

We will need a simple database table for our user data. Something like this:

  `name` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
  `username` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `password` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`id`)

-- Dumping data for table `users`

INSERT INTO `users` (`id`, `name`, `username`, `password`) VALUES
(1, 'Demo', 'demo', 'demo123');

Next, we will build a login form:

<form action="" method="post" id="form">
    <input type="text" id="username" name="username" />
    <input id="password" type="password" name="password" />
<div id="message" style="display:none;"></div>

As you can see, I created a div with id of message, which will hold the response from server later on.

Let’s create some jQuery magic:

$(function() {
    $('#password').keyup(function() { // when we release the key
        var pass = $('#password').val();
        if(pass.length >= 3) { // if there are more then 3 letters
            var data = 'username='+ $("#username").val() + '&amp;pass=' + pass;
            // ajax call
                type: "POST",
                url: "login.php",
                data: data,
                success: function(html){ // this happen after we get result
                    if(html !== '') {
                        $("#form").hide(); // hiding form

This code is triggered after a key has been released on password field. It counts the characters, and as soon as there are 3 or more of them, it sends an AJAX request to login.php file which looks like this:

if($_POST) {
    /*** mysql hostname ***/
    $hostname = 'localhost';

    /*** mysql username ***/
    $username = 'root';

    /*** mysql password ***/
    $password = '';

    $dbname = 'demo';

    try {
        $dbh = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password);
        // getting and escaping POST variables
        $user = addslashes(strip_tags($_POST['username']));
        $pass = addslashes(strip_tags($_POST['pass']));

        /*** set all errors to execptions ***/
        $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
       /*** checking username and password ***/
        $sql = "SELECT count(*) AS total FROM users
                WHERE username = :user AND 
                password = :pass";
        $stmt = $dbh->prepare($sql);
        /*** bind the paramaters ***/
        $stmt->bindParam(':user', $user, PDO::PARAM_STR);
        $stmt->bindParam(':pass', $pass, PDO::PARAM_STR);
        if ($stmt->fetch(PDO::FETCH_COLUMN) > 0) {
            $sql = "SELECT * FROM users
                    WHERE username = :user AND 
                    password = :pass";
            $stmt = $dbh->prepare($sql);
            /*** bind the paramaters ***/
            $stmt->bindParam(':user', $user, PDO::PARAM_STR);
            $stmt->bindParam(':pass', $pass, PDO::PARAM_STR);
            $row = $stmt->fetch(PDO::FETCH_ASSOC);
            // here we write $row to $_SESSION
            $_SESSION['User'] = $row;
            // sending user's name back as result
            echo '<p>Congratulations, <em>' . $row['username'] . '</em>, you have successfuly logged in!</p>';     
    catch(PDOException $e) {
        echo $e->getMessage();


This is simple, we are declaring some db connection variables at the top, then connecting to database using PDO class. Then we count rows from the database where username and password match those entered in the form. If there is no such user in the database, nothing happens, but if we find such a user PDO fetches user data from database and store it to the SESSION. At the end, we are sending a nice message back to the Javascript as response.

jQuery scripts is controlling the response, and as soon as it is not empty, it is hiding the form and appending our response message to message div.

I would like to see your opinion on using this method on a live site, so do not hesitate to comment. This is an experiment and probably not so good to use on login form, but interesting to play with.

Tweet about this on TwitterShare on FacebookShare on Google+Share on LinkedInShare on RedditShare on StumbleUpon

  • Luka Kladaric

    oh… god… where to start?

    1) solution in search of a problem

    2) bandwagon jumping

    3) publishing trivial code and calling it magic

    3) effectively brute-force attacking yourself, good luck figuring out if someone’s trying to hack you…

    4) also good luck scaling this to thousands of active users

    5) browser password remembering?

    6) while we’re at it, reacting to browser saved passwords?

    7) sql injection vulnerability – http://shiflett.org/blog/2006/jan/addslashes-versus-mysql-real-escape-string

    you could’ve added google suggest to the login form while you’re at it… or a little dropdown for both usernames and passwords, if you match the correct username and password, you log in!

    awesome SEO here tho… great headline, most useless post ever

    and to finish, a colleague’s comment:
    [2010-09-28 23:45:46] Sasha Lerner: you can quote me as the most braindead blog post i’ve ever seen 🙂

    • Zvonko

      @Luka Thanks for your comment. I did not call this magic, I said let’ add some jQuery magic.

      Maybe it is trivial to you and me, but this blog is for beginners, too.

      This tutorial is meant to be an experiment. Obviously, login form is not such a great place to use it.

      I corrected the addslashes and added strip_tags. If you read the tutorial more carefully, I am using PDO and thus can not use mysql_real_escape_string function. I am binding parameters now to make it bulletproof and using a prepared statement.

      Thanks anyway

  • Luka Kladaric

    also – two queries where one will do just fine

    • Zvonko

      I wanted to show how to use count(*) with PDO. And count(*) is optimized and much faster then any other solution.

      Second query is executing just once, anyway.

  • Cool idea, but I’d prefer to see this technique applied out of login forms, which are by nature a delicate matter.

  • Peter Gasston

    The lack of any kind of feedback is disconcerting; I don’t know whether my username is wrong, my password is wrong… really confusing. I can’t see how this is an improvement on a standard login form.

    • Obviously it’s just the “instant” feature allowing users to login slightly fater… feel free to add your own custom error messages but as stated, this is just a fun experiment!

      I think it’s pretty cool but because of the obvious security risks I’d never implement it. It’s also bad for auto form fillers, I use LastPass and depending on how you detect form changes entering a username and password might not be detected.

  • Thomas Schaaf

    Security wise this seems extremly bad, since this would allow for bruteforce attacks to take place and you not even being able to block them. That is why this will never be implemented in this way.


  • Zvonko

    Thanks for all comments.

    I have to agree that using this on login form is a bad idea. But it was fun doing it, and it shows several techniques people can use in a more convenient places .

  • Boba

    Sto bi se reklo kod nas na Balkanu, “Ko ce koga ako ne svoj svoga”.

    Al, ajde, kad dva zemljaka mogu medjusobno da pricaju na engleskom i ja cu (nisam vam zemljak, da ne bude zabune).

    @Zvonko – As they all said, there are problems with this, but it’s a nice experiment and it can be used on something else besides login (username availability checking for example).

    @Luka – Take it easy man, no need to insult people just because they made a little mistake. If you left a comment like that on my blog i wouldn’t even approve it, not because it says that i’m wrong, i like that kind of comments, you learn more on errors then you do on successes, but you are just being rude and that’s why it would be deleted.

    Keep it up Zvonko and greetings from a Serbian developer.

  • SAB

    At least add notes on the start that this script is not for live use.

    All login forms I made have uses at least token string and mysql_real_escape_string…

    I must say that this effect looks nice but this code is the biggest enemy to all PHP beginners… They will learn the WRONG way….

    • Zvonko

      @SAB I already mentioned that I am using prepared statement with PDO class and binding the parameters. So, the user input is secure!

      I can not use mysql_real_escape_string as I am using PDO class for database handling.

  • Josh

    Interesting concept. Would never be able to use this in the real world, but Jquery experiments are always fun. @Luka We all see those problems, you don’t have to be an asshole about it.

    • Izkata

      He’s right, though, and just made a nice list about it.

      5 and 6 are the big ones from the end-user perspective, as this completely breaks the password-storing features of browsers.

  • hi,


    can be written as


  • David

    Well, I’m a beginner at jQuery so I found it somewhat helpful as far as syntax, etc. goes.

    Have a great day!

  • Haso K.

    I think the mySQL table is pretty bad 255’s for username and password… 😮