Welcome Guest, Not a member yet? Register   Sign In
CI + jQuery modal login tutorial
#1

[eluser]Loquela[/eluser]
Hi there,

Could anybody point me to any good tutorials about using CI + jQuery for creating a modal form submition (login or registration, etc..)?

Cheers,

L.
#2

[eluser]treeface[/eluser]
Can't find any good tutorials, but I'll tell you how I do it.

Basically you have a login form anywhere on your page. Something like this:

Code:
<form action="/user/loginsubmit" method="post" class="login_form">
    <label for="login_form_username"><strong>Username:</strong></label>
    &lt;input id="login_form_username" type="text" maxLength="25" tabindex="1" name="username" /&gt;
    <a href="/recover">recover username</a>
    <label for="login_form_password"><strong>Password:</strong></label>
    &lt;input id="login_form_password" type="password" tabindex="2" name="password" /&gt;
    <a href="/recover">recover password</a>
    <div class="clearleft"></div>
    &lt;input id="login_form_submit_button" type="submit" value="Log in" tabindex="3" /&gt;
    <div class="ajax_loader"></div><div class="confirm_text"></div><div class="clearleft"></div>
&lt;/form&gt;

So...basically it's just a simple list of inputs. At the bottom I have a div with class '.ajax_loader' which has a background of a swirly gif of some sort. ".confirm_text" is another reusable class of mine that I use to display ajax messages. You'll also notice that this is all in a form with the proper uri targets, so if a user doesn't have javascript turned on, it goes to the login function in the user controller as a regular form post request. Now for the ajax..

Code:
$(document).ready(function() {
$('.login_form').submit(login);
})

function login(e) {
var data = new Object();
    data.username = $('#login_form_username').val();
    data.password = $('#login_form_password').val();
    
    if (data.username == '' && data.password == '') {
        alert("Please enter your username and password.");
        return false;
    } else if (data.username == '') {
        alert("Please enter your username.");
        return false;
    } else if (data.password == '') {
        return false;
        alert("Please enter your password.");
    }
    
    var post = new Object();
    post.data = $.toJSON(data);
    
    $('.ajax_loader', $('.login_form')).show();
    
    $.post("/user/loginsubmit", post, function(textdata) {
        $('.ajax_loader', $('.login_form')).hide();
        var confirmText = $('.confirm_text', $('.login_form'));
        $(confirmText).show();
        
        var data = $.evalJSON(textdata);
        
        if (data.success) {
            $(confirmText).css('color', '#39B15B');
            $(confirmText).text("Success! Redirecting...");
            
            if([removed].pathname == "/login") {
                [removed].pathname = "/";
            } else {
                [removed].href = [removed].href;
            }
        } else {
            $(confirmText).css('color', '#e31b23');
            $(confirmText).text(data.result);
        }
    }, "text");
    
    return false;
}

So there you can see that my AJAX post gets sent to the same controller function as my form path. Inside my controller, I have a conditional to check if it's JSON or not...something like....

Code:
function loginSubmit() {
if (isAjax()) {
$data = json_decode($this->input->post('data'));
$username = $data->username;
$password = $data->password;

if ($username == '' || $password == '') {die(json_encode(array('success'=>false, 'result'=>"Please provide both a username and a password")));}

//load the user model and send data to it to check it against the DB and then set up the session userdata
$this->load->model('user_model');
$returnObject = $this->user_model->login($username, $password);

//kill script and return json encoded array to be evaluated by JS
die(json_encode($returnObject));
} else {
//if it isn't ajax, presumably the user submitted the login form without javascript
$username = $this->input->post('username');
$password = $this->input->post('password');

//do form validation stuff here and so on...

$returnObject = $this->user_model->login($username, $password);
}
}

So when you return your thing to javascript, as you can see in the JS login function above, you can redirect the page to where ever you want using javascript if the login is successful or display the error message if it isn't.

<b>Edit:</b> by the way, that "isAjax()" function is a helper I have called isajax_helper.php. It goes something like this:

Code:
&lt;?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* is_ajax_call
*
* Determines if the current page request is done through an AJAX call
*
* @access    public
* @param    void
* @return    boolean
*/
if ( ! function_exists('isAjax')) {
    function isAjax() {
        return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest';
    }
}
?&gt;
#3

[eluser]Loquela[/eluser]
Dude, that was above an beyond the call of duty!! Much appreciated, thanks.
I've not had chance to test it yet, but it's a great help to understand the principle.

Cheers!

L.
#4

[eluser]treeface[/eluser]
No worries :-)

Another btw for you...not sure if you're aware, but if you notice the "return" values in my javascript function are boolean. This is a technique known as "hijax". Basically, it allows you to build out your site for both javascript users and those with it turned off. Let's say you have a list of a user's addresses. Each address is an anchor element styled to make it look all fancy-like. When a user clicks it, you want a box next to this address list to be populated with the address details so a user can edit them. If a user does not have javascript, you want the link to take them to another page where the PHP (CI, or w/e framework you're using) will populate the fields. The anchor looks like this:

Code:
<a id="address_&lt;?php echo $address_id?&gt; href=" class="address_list_link">
&lt;!-- put whatever in here --&gt;
</a>

Then in your jquery...

Code:
$(document).ready(function(){
$('.address_list_link').click(function(e) {
var address_id = $(this).attr('id').substr(8);

//send your address id off to php in a post request to get the details

//this is the important bit that will kill the html execution of the anchor element click
return false;
});
});

So you can see, if you have an event listener attached to the "click" event of an anchor (or the "submit" event of a form), you can cancel the normal execution. This is why it's called "hijax" cuz you're sort of "hijacking" the "normal" execution if the user has javascript, but it degrades gracefully for those without it. And so if you look back up at my original post, I have "return false" in a few places in that javascript function so it doesn't do a non-ajax form submission. When it gets word back that the login was successful, it changes the color of ".confirm_text" to green, puts the text "Success! Redirecting..." in there, and then uses javascript to change the window's location (basically it just does a reload...which is a very useful feature once you spend a few minutes using it). Looks fancy, smells fancy, is fancy.
#5

[eluser]Loquela[/eluser]
This is great, thanks. Accessibility is very important for my clients so this is all good.

L.
#6

[eluser]treeface[/eluser]
You're very welcome. Be sure to post back here if you have any issues.




Theme © iAndrew 2016 - Forum software by © MyBB