Using jQuery and CodeIgniter for a AJAX Login
June 24th, 2008 | by Isern Palaus |One of the most problem when the people starts coding is the needed of another to see what to do. The user guide of CodeIgniter is one of the best, okay the best, I’ve ever read, but sometimes the newbies needs more. Now it’s my time and I’ll try to explain how to do a little AJAX Login.
For this we need the last jQuery, you can download it on the official jQuery website. Then, obviously, Code Igniter.
We will start with the database. It’s simple because usually I separate the user from her profile.
1 2 3 4 5 6 7 8 | CREATE TABLE `users` ( `uid` int(10) NOT NULL AUTO_INCREMENT, `username` varchar(16) NOT NULL, `password` varchar(32) NOT NULL, `email` varchar(128) NOT NULL, `time` int(10) NOT NULL, PRIMARY KEY (`uid`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; |
In this tutorial I’ll use md5, I prefer SHA-1 but the site I developed I used md5… Using md5 or SHA-1 only takes changes when you encode/decode the password on the registration and check if are equals on login, nothing more. Then, I’ll start with the controller and the model.
It’s called user and it controls the register/login/logout but I’ll only show the second term.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 | <?php if (!defined('BASEPATH')) exit('No direct script access allowed'); class User extends Controller { function User() { parent::Controller(); $this->load->model("user_model"); $this->load->model("dalia_model"); $this->load->helper("security"); $this->load->helper("form"); } /* Checks if the password that the user gives is equal at the DB ones */ function _check_login($username) { $password = md5($this->validation->password); if(!$this->user_model->checkUserLogin($username,$password,"users")) return FALSE; return TRUE; } function index() { $this->load->view("userLogin"); } function checkLogin() { $this->load->library('validation'); $rules['username'] = 'trim|required|callback__check_login'; $rules['password'] = 'trim|required'; $this->validation->set_rules($rules); $fields['username'] = 'username'; $fields['password'] = 'password'; $this->validation->set_fields($fields); if ($this->validation->run()) { $username = $this->validation->username; $uid = $this->user_model->getUserId($username,"users"); $this->session->set_userdata("logged_in",$uid); $output = '{ "success": "yes", "welcome": "Welcome" }'; } else { $output = '{ "success": "no", "message": "This is not working" }'; } $output = str_replace("\r", "", $output); $output = str_replace("\n", "", $output); echo $output; } function logout() { $this->session->sess_destroy(); redirect(""); } } ?> |
With jQuery we need a function that returns to the script the output. This function is checkLogin(), later you will see where I used it. If you look at this function now, you can see how I validate the terms. At the first rule:
$rules['username'] = 'trim|required|callback__check_login';
I use a callback to _check_login to check the if the username and password is valid. If we look to this function you will see that it uses a model:
function _check_login($username) {
$password = md5($this->validation->password);
if(!$this->user_model->checkUserLogin($username,$password,"users"))
return FALSE;
return TRUE;
}
First we encrypt the $password term from the form to md5, because we already have the password in md5 at database. Then we check if the content of the checkUserLogin is NULL or not. If it’s NULL its because the username/password aren’t valid. Else, it’s TRUE
. Then its time for the model:
It’s named user_model.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | <?php class User_model extends Model { function __construct() { parent::__construct(); } function checkUserLogin($username,$password,$table=users) { $query = $this->db->where("username",$username); $query = $this->db->where("password",$password); $query = $this->db->limit(1,0); $query = $this->db->get($table); if ($query->num_rows() == 0) { return NULL; } return TRUE; } } ?> |
You can see that the function checkUserLogin gets the $username, $password and $table (I EVER use $table in my functions because if I need use this user system in another project probably the user table is named differently (It’s ever user but in case…)).
A simple database class use that checks first for the username and later for the password. If the num_rows() returned is equal a 0 it is because isn’t valid. Else we return TRUE.
Now we have the checkLogin working. It’s time to see how to use it on a view. The controller is simple, because this login doesn’t needs that. Only a $this->load->helper(”form”);.
I named my view baseHeader.php because I want to see the AJAX login on EVERY page:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en"> <head> <link href="<?=base_url();?>content/css/main.css" rel="stylesheet" type="text/css" /> <script language="javascript" type="text/javascript" src="<?=base_url();?>content/js/jquery/jquery-latest.js"></script> <script language="javascript" type="text/javascript" src="<?=base_url();?>content/js/jquery/jquery.form.js"></script> <script language="javascript" type="text/javascript" src="<?=base_url();?>content/js/user.js"></script> <meta http-equiv="Content-Type" content="text/html;charset=utf-8" /> </head> <body> <div id="content"> <div id="header"> <div id="login"> <?php if($this->session->userdata('logged_in')) { ?> <div id="logged"> Welcome, you're already logged In. </div> <?php } else { ?> <div id="loginform"> <?=form_open('user/login',array('id' => 'userlogin'));?> <label for="username">Username:</label> <input class="logininput" type="text" name="username" id="username" /> <label for="password">Password:</label> <input class="logininput" type="password" name="password" id="password" /> <input class="loginsubmit" type="submit" value="Login" /> <?=form_close();?> </div> <div id="logged"></div> <div id="loginerror"></div> <?php } ?> </div> </div> <div id="body">
This a simple form with form_open. I used a action on it for the non-JS browser can login. Then check the two divs with id logged and loginerror. This two are needed, we can use only one but I prefer two. (In the second I’ve on the CSS a color:red;).
The jQuery file is so simply, it looks like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 | $(document).ready( function(){ $("#userlogin").ajaxForm({ type: "POST", url: "http://localhost/dalia/trunk/public_html/index.php/user/checkLogin", dataType: "json", data: "username="+$("#username").val()+"&password;="+$("#password").val(), success: updateLogin }); } ) |
You can see how I use the ids to set the jQuery form. For use ajaxForm we will need the jQuery Form plugin you can download it on the official webpage for the jQuery form or the jQuery Plugins section.
type: "POST", // We use post for the login form url: ""http://localhost/dalia/trunk/public_html/index.php/user/checkLogin", // We will call the function of the user controller dataType: "json", // Its the type of the data we send. A json looks like: { "success": "yes", "message": "in a bottle" } data: "username="+$("#username").val()+"&password;="+$("#password").val(), // The data we sent to the url, the inputs of the form have id=username and id=password success: updateLogin // What happens when the function success I personally separate this from the ajaxForm
Now the updateLogin function, it will be used to update the are of the login:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | function updateLogin(data) { $('#logged').html(''); $('#logged').hide(); $("#loginform").fadeOut("slow", function() { if (data.success == 'yes') { $('#logged').html(data.welcome).fadeIn("slow"); } if (data.success == 'no') { $('#loginerror').html(data.message).fadeIn("slow").fadeOut("slow", function() { $("#loginform").fadeIn("slow"); } ); } } ); } |
Its so easy, if data.success send by the controller isn’t valid we show de data.message in the #loginerror id (remember the div) and the login appears another time. If the data is valid the form disappears and we write the data.message.
And then… It’s now working. Remember to check that you included the correct javascript files on the view before start asking.
9 Responses to “Using jQuery and CodeIgniter for a AJAX Login”
By Isern Palaus on Jun 24, 2008 | Reply
Testing Gravatar addition to the BigBlue Theme by Bob.
By Craig on Jun 26, 2008 | Reply
Great tutorial. Nice to see tutorials using these great tools together.
By ken-G on Jun 26, 2008 | Reply
cool tutorial, looking forward for more tuts , i just started with codeigniter
By Anuj on Jul 9, 2008 | Reply
Nice Tutorial…But can you please provide me the files in zip format so that I could download them from this site?
By Matt on Aug 6, 2008 | Reply
In the model you keep re-assigning the variale $query. How is this supposed to work.
By Isern Palaus on Aug 25, 2008 | Reply
Hello,
Thank you all for the cheers.
Matt, this is because we are using a modified version of Active Record Class. You can do this too:
And will work like a charm!
Regards,
– Isern Palaus
By speedovation on Sep 27, 2008 | Reply
Nice tutorial !! searching for such an easy way to implement ajax in CI.
Thank you
By Jon on Oct 6, 2008 | Reply
I see “user_model” in your explanation (class User_model extends Model) … however, you’re also loading “dalia_model” — I don’t see that code in the tutorial.
By Jon on Oct 6, 2008 | Reply
Also, where does the updateLogin function go? In user.js? Above $(document).ready( ??