jQuery Live Login inspired by Google Instant Search
19 comments
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:
CREATE TABLE IF NOT EXISTS `users` ( `id` int(11) NOT NULL AUTO_INCREMENT, `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`) ) ENGINE=MyISAM ; -- -- 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">
Username:
<input type="text" id="username" name="username" />
Password:
<input id="password" type="password" name="password" />
</form>
<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() + '&pass=' + pass;
// ajax call
$.ajax({
type: "POST",
url: "login.php",
data: data,
success: function(html){ // this happen after we get result
if(html !== '') {
$("#form").hide(); // hiding form
$("#message").append(html);
$("#message").fadeIn(800);
}
}
});
}
});
});
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);
$stmt->execute();
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);
$stmt->execute();
$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.
To get even more excellent content, you can follow me on Twitter.
19 Responses to “jQuery Live Login inspired by Google Instant Search”
-
-
-
Giorgio Sironi says:
Cool idea, but I’d prefer to see this technique applied out of login forms, which are by nature a delicate matter.
-
Peter Gasston says:
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.
-
Jean-Patrick Smith says:
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 says:
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.
Thomas
-
-
Boba says:
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 says:
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….
-
Josh says:
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 says:
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.
-
-
designfreek says:
hi,
$(“#message”).append(html);
$(“#message”).fadeIn(800);can be written as
$(“#message”).append(html).fadeIn(800);
-
David says:
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. says:
I think the mySQL table is pretty bad 255′s for username and password…
-
Bindi says:
I like the simple jquery example w/ajax. This helped me develop a different idea where ajax calls were firing based on keypress. I don’t care if it’s secure, I just wanted a good keypress example with ajax and jquery and this is just right. thanks.
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