Home > Web dev > Quick Ajax Register and Login

Quick Ajax Register and Login

October 11th, 2009

code 150x150 Quick Ajax Register and LoginRegistration and login forms play a massive part in thousands of websites now and getting this right can be a very important part in building your site. I belive that registration should be a very easy process for the user. Some websites (IMDB) make it so hard to register and validate your account. So in this tutorial we will be keeping simplicity in mind.

Source | Demo – Source has a dump of the MySQL database

We will be using the ajax plugin for jQuery so first of all download that from here and save it as ajax.js. Now lets get the basics out of the way. I wont go through the HTML and CSS here as there is nothing special going on.

<div id="container">
	<div class="box" id="register">
    	<form action="register.php" method="post" id="register_form">
        	<p>Username <input type="text" name="username" id="reg_username" /></p>
            <p>Email <input type="text" name="email" id="reg_email" /></p>
            <p>Password <input type="password" name="password" id="reg_password" /></p>
            <p>And again... <input type="password" name="2ndpass" id="reg_password2" /></p>
            <p><input type="submit" value="Register" /></p>
        </form>
        <p id="register_callback"></p>
    </div>
    <div class="box" id="login">
    	<form action="login.php" method="post" id="login_form">
        	<p>Username <input type="text" name="username" id="login_username" /></p>
            <p>Password <input type="password" name="password" id="login_password" /></p>
            <p><input type="submit" value="Login" id="login_btn" /></p>
        </form>
        <p id="login_callback"></p>
    </div>
</div>
body{
 font-family: Verdana, Geneva, sans-serif;
}
#container{
 width: 700px;
 margin: auto;
}
.box{
 width: 350px;
 margin-right:-20px;
}
#register{
 float: left;
}
#login{
 float: right;
}
p input{
 float: right;
}

Now for the jQuery. The first bit we will look at is the registration form ajax. This will go on the same page as the login form.

$('#register_form').ajaxForm({
 target: '#register_callback',
 success: function(data){
 $('#register_callback').html(data);
 }
 });

ajaxForm() calls the ajax plugin we are using. There are also an array of options here. We are using target to define what element will be updated when the ajax call is complete. And success to define the function to be executed when we register.

This is the PHP for the registration form.

<?php
include_once('db.php');
$username = mysql_real_escape_string($_POST['username']);
$email = mysql_real_escape_string($_POST['email']);
$password = mysql_real_escape_string($_POST['password']);
$password2 = mysql_real_escape_string($_POST['2ndpass']);

//Check if the username exists
$username_query = mysql_query('SELECT id FROM users WHERE username = "'.$username.'"');
$username_check = mysql_num_rows($username_query);
if($username_check == 0){
	if(!preg_match('/^([a-z0-9])(([-a-z0-9._])*([a-z0-9]))*\@([a-z0-9])' . '(([a-z0-9-])*([a-z0-9]))+' . '(\.([a-z0-9])([-a-z0-9_-])?([a-z0-9])+)+$/i', $email)){
		echo 'Invalid email address';
	}
	else{
		if($password == $password2){
			$register = mysql_query('INSERT INTO users (username, password, email, messages) VALUES ("'.$username.'", "'.md5($password).'", "'.$email.'", "'.rand(1, 500).'")');
			if($register){
				echo 'Successfully registered with the username '.$username;
			}
			else{
				echo 'Registration failed, please try again';
			}
		}
		else{
			echo 'Passwords don\'t match';
		}
	}
}
else{
	echo 'Username taken';
}
?>

Now to do the login bit.

Firstly the PHP so we can make sense of the jQuery

<?php
include_once('db.php');
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);

$query = mysql_query('SELECT * FROM `users` WHERE username = "'.$username.'" LIMIT 1');
$query = mysql_fetch_array($query);
if(md5($password) == $query['password']){
?>
<ul>
    <li>Username: <?=$query['username']?></li>
    <li>Email: <?=$query['email']?></li>
    <li>Messages: <?=$query['messages']?></li>
</ul>
<?php
}
else{
	echo 'Incorrect password';
}
?>

So there you can see we select all from the users table. Then we encrypt the password into an md5 string and compare it with the database. If it passes this test it will let the user through and show them a few details. If not it will return “incorrect password.

Now the login jQuery. Again this will go on the same page as the login form.

$('#login_form').ajaxForm({
			success: function(data) {
				 	if(data == 'Incorrect password'){
						$('#login_callback').html(data);
					}
					else{
						$('#login').html(data);
					}
			}
		});
share save 171 16 Quick Ajax Register and Login

Web dev Tags:, ,

Related posts » Top jQuery plugins and tutorials in 2011
» 50 Awesome Animations using CSS3
» 25 Useful Html5 Cheat Sheets and Tutorials For Web Developer
» 7 Best Mobile Web HTML5 Framework For Mobile App Development
» 10 Common Useful PHP Regular Expression