Welcome Guest, Not a member yet? Register   Sign In
[TUTORIAL] *UPDATED* Using jQuery and CI for a AJAX Login (v0.2) + example rar
#21

[eluser]ikhnaton2[/eluser]
Yes I see the login form and there should be 3 cases:
1. Write nothing in username/password and hit login
This was not working until i change all shorthand <?=...> into <?php echo ...>
Now, it writes "This is not working" and come back to login form which is expected as it violated validation rules.

2. Write incorrect data and hit login -> nothing happen, page stay with the login form

3. Write good username/password and hit login same as #2

Questions for better understanding:

1. Where should the form go when press "Login", form opening says "user/login" as:
Code:
<?=form_open('user/login',array('id' => 'userlogin'));?>
but there's no function in the "user" controller called "login".

2. In "user" controller, "checkLogin" function, there's a line:
Code:
$uid         = $this->user_model->getUserId($username,"users");
but there's no "getUserId" in "user_model" class

Thanks for advising
#22

[eluser]herrmoinsen[/eluser]
Thanks for the great tutorial! It's very nice and good to understand.

Unfortunately it is not working for me. Everythings fine until it try to login. If my form is empty and I hit the "login"-button it says "This is not working" - fine. But IF there is some data (correct or incorrent login doesn't matter) the form / jquery does NOTHING.

Any suggestions? Thanks a lot.
herrmoinsen
#23

[eluser]polish[/eluser]
Hi!

Thanks for the nice tutorial, but it doesn’t work with me!!!

I have the same problem as ikhnaton2 and herrmoinsen!!!

Isern Palaus explain me (ikhnaton2 and herrmoinsen too) what it is necessary to do so that everything works ok???
#24

[eluser]marjune[/eluser]
eh i try that idea but it dosent work the jquery when i log in

here my code

view

<center>

&lt;?php form_open('helloworld/login',array('id' => 'userlogin'));?&gt;
<label for="username">Username:</label>
&lt;input class="logininput" type="text" name="username" id="username" /&gt;
<label for="password">Password:</label>
&lt;input class="logininput" type="password" name="password" id="password" /&gt;&lt;br />
&lt;input class="loginsubmit" type="submit" value="Login" /&gt;
&lt;? form_close();?&gt;

//if($this->session->userdata('logged_in')) {

[removed]

$(document).ready(
function data(){

$("#userlogin").ajaxForm({
type: "POST",
url: "http://localhost/ci/index.php/helloworld/checklogin",
dataType: "json",
data: "username="+$("#username").val()+"&password;="+$("#password").val(),
success: updateLogin
});

}
)


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");
}
);
}
}
);

}
[removed]
</center>


i want only to execute the jquery when i log in then i take the rest!!!!thankss

please help!!!!!!!!
#25

[eluser]Isern Palaus[/eluser]
Hello,

Tonight I'll try to recuperate this project and show all the code and source to be more clarify. Try it then and check if now is working. If not, I'll be here to answer your questions.

Regards,
Isern
#26

[eluser]Isern Palaus[/eluser]
ipalaus-ajaxlogin v0.2 here!
Hello,

This is my revision of the tutorial I wrote more than a year ago. This will be practicaly the same but with all files you need and a downloadable .zip file.

For this people that are looking for a full working auth system with registration, I've to say that I don't have time to do it all by myself in this tutorial. So, like I did in my earlier days in CodeIgniter, we will base this on a pre-existing full user system. I base this code on the fantastic auth library by Popcorn, called 'Redux Authentication' (v2 beta).

Ok, let's go!

The first thing we need to do is download the Redux Authentication 2 Beta. Go to the Google Code project and download it here. You can also go to the official post to ask about the library. We will work with the login, I've nothing to do about registration and users managament. Sorry.

When you download the pack you will see that, inside, there is a folder called 'Example Application'. We will use this application but we need to update it to the last CodeIgniter version. The way to do this is very simple. Download CodeIgniter (really?) and unrar it. Then go to 'Example Application', rename it to ajaxlogin (I'll use this name in my examples). Enter to it and then enter to /system. Delete ALL the folders unless the application folder, where is the application located. Go to the downloaded CodeIgniter version and copy paste the folder you deleted (unless the /application folder). The detailed, and oficial, guide to upgrade can be found here. Check it!

Then install the database and configure it. The first thing you've to do is add a group called 'members' in the group:
Code:
INSERT INTO groups (`id`, `name`, `description`) VALUES (NULL, 'member', 'Members')

In the config/redux_auth.php you will see that there is a default group to set. In the database we don't have data so we need to add a default grup and set it on the config file. Other recommendation is set activation to false because its not working at all. There are another variables that we can change, like the login method (username, email...). I chose the default, the email. Change to username its not complicated. Try it and if it doesn't works i'll code it.
Code:
$config['email_activation'] = false;

Now you can go to your page (configure other things in config.php, like you'll do if you're installing a new CI).

First thing: create a user. Then try to login. You will be redirected to status and see bool(true) if login is sucessful. Now its time to code our AJAX login.

Time to code. Go to /system/application/views/template.php and add between &lt;head&gt; and &lt;/head&gt; the jQuery Library that you've downloaded:
Code:
&lt; script type="text/javascript" src="&lt;?php echo base_url().'assets/js/jquery-1.3.2.min.js'; ?&gt;"&gt;&lt;/ script>
&lt; script type="text/javascript" src=&lt;?php echo base_url().'assets/js/ajaxlogin.js'; ?&gt;"&gt;&lt;/ script>
Note: You have to change &lt; script. I also added the ajaxlogin.js file that we will use for the login.

In this case, the difference between the other script, is that we will use the Redux login function and this will optimitze our code. In the welcome controller we will add two functions:

Code:
function _check_login($email)
    {
        return $this-&gt;redux_auth->login($email, $this->password);
    }
    
    function ajaxLogin()
    {
        $this->load->library('validation');
        
        $this->password = $this->input->post('password');
        $this->loginemail = $this->input->post('email');
        
        $this->form_validation->set_rules('email', 'Email Address', 'trim|required|callback__check_login');
        $this->form_validation->set_rules('password', 'Password', 'trim|required');
        
         if ($this->form_validation->run() == false)
        {
            $data = array(    'success' =>    'no',
                            'message' =>    'The email or password you provided are wrong.');
            
            $output = json_encode($data);
        }
        else
        {
            $data = array(    'success' =>    'yes',
                            'welcome' =>    'Welcome '.$this->loginemail.'!');
            
            $output = json_encode($data);
        }
        
        $output = str_replace("\r", "", $output);
        $output = str_replace("\n", "", $output);
        
        echo $output;
    }
#27

[eluser]Isern Palaus[/eluser]
To understand the code. The first function, _check_login, uses the redux_auth_model.php to validate the e-mail account and the pass provided. Check it on the models folder for more information. If the information provided are correct will return TRUE. Else, will return FALSE. In case that TRUE is returned, the model sets on the session our email. If you need another thing, modify the model.

The second function is a mix of the Redux login function and my ajax login function. It takes the two input forms and validates it. The first, the e-mail one, uses the callback method to call a function (_check_login). If all the information provided is FALSE, or something is wrong. Then we will pass the data to the ajax function encoding it with JSON. The information encoded is like: { "success": "no", "message": "The email or password you provided are wrong." }.
If the information was correct another data will be encoded and sended to the ajax function.

By the way, note that I used $this->password and $this->loginemail. This variables have to be defined in the top of the controller. Like that:
Code:
class Welcome extends Controller {

    private $password     = NULL;
    private $loginemail    = NULL;
    
    /**
     * index
     *
     * @return void
     * @author Mathew
     **/
    function index()
    {
        redirect('welcome/status');
...

Okay! Now we will modify the login. As you know, the best way to learn to create a form is going to the user guide. So, open /views/login.php. When we have a login form we usually like to show only when the user is not logged in. In the Redux example this do not happens and we've a way to modify it. The way is to check in the session is the identity item added. Add to the first line this code:
Code:
&lt;?php
if($this->session->userdata($this->config->item('identity')))
{
    echo "<h1>You're aready logged in!</h1>";
}
else {
?&gt;
<h1>Login</h1>

This will check if the data is set. Normaly we will use $this->session->userdata('email') (or username) but we have in the config a variable to set the identity. Let's take advantage of it. At the end of the file add:
Code:
&lt;?php
}
?&gt;

You can check it. Log in and return to login page. It will show a 'You're already logged in".

We've to add some more lines to the login.php file. Change the form_open to add a id, add a id to the table, add to extra divs to show a error message or succesful message, add ids to the form inputs to identify it:
Code:
&lt;?php echo form_open('welcome/login',array('id' => 'userlogin')); ?&gt;

Code:
<table id="loginform">

Code:
<div id="logged"><div>
<div id="loginerror"></div>
I situated this two divs after the form_close().

Change:
Code:
<td>&lt;?php echo form_input('email', set_value('email')); ?&gt;</td>
To:
Code:
<td>&lt;input type="text" name="email" value="&lt;?php set_value('email'); ?&gt;" id="email" /&gt;&lt;/td>
And:
Code:
<td>&lt;?php echo form_password('password'); ?&gt;</td>
To:
Code:
<td>&lt;input type="password" name="password" value="" id="password" /&gt;&lt;/td>
Note: You've to remember that we are using email to login. If you want a username you will have to change name="email" to username and id="email" to username too.

Now its time to code the javascript file. Remember that we added it with the jquery library. Create a .js file called ajaxlogin.js in /assets/js/ . To use the ajaxForm function we will need a plugin. You can download here. Added it like we did with the other two files (in template.php):
Code:
&lt; script type="text/javascript" src="&lt;?php echo base_url().'assets/js/jquery.form.js'; ?&gt;"&gt;&lt;/ script>
Note: remember to change &lt; script to &lt;script .

Now write on ajaxlogin.js this code:
Code:
$(document).ready(
    function(){
    
        $("#userlogin").ajaxForm({
            type: "POST",
            url: "http://localhost/ajaxlogin/index.php/welcome/ajaxLogin",
            dataType: "json",
            data: "email="+$("#email").val()+"&password;="+$("#password").val(),
            success: updateLogin
        });
    
    }
)
Note: If you want to use the username change email="+$("#email") to username="+$("#username") .

At this point, the script will work... but we have to implement a function that is called in the ajaxForm when success:
Code:
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");
                    }
                );    
            }
        }
    );
    
}

This will do an animation and will make disappear the form. It also will write the data passed with json to the div that we've specified.

It's working! Oh yeah! Tested it with FireBug and all goes fine.

DOWNLOAD:
- ipalaus-ajaxlogin-v0.2.rar

PS: Sorry for my English ;-)

See you soon!
#28

[eluser]Unknown[/eluser]
hi..

how about security issue when using ajax? is it safe?

thanks.. Smile
#29

[eluser]arlabbafi[/eluser]
thanks a lot for this tutorial
where is link of download ??
#30

[eluser]Isern Palaus[/eluser]
At the bottom:

DOWNLOAD:
- ipalaus-ajaxlogin-v0.2.rar

cobbydict,

I can say how secure is ajax but I supose that is the same as using a input with no ajax content. If someone can tell us it will be helpful.

Thanks!




Theme © iAndrew 2016 - Forum software by © MyBB