Love Fuel?    Donate

FuelPHP Forums

Ask your question about FuelPHP in the appropriate forum, or help others by answering their questions.
AJAX Login - With Template
  • I'm trying to do an AJAX'd login with a template. The login worked fine on it's own, but as soon as I added AJAX with a redirect variable it's not going to the same place upon successful login and, it's probably a really simple fix, but I'm lost as to what to do next. My index controller: <?php
    class Controller_Index extends Controller_Template
    {
    public function router($resource, array $args)
    {
    $auth = Auth::instance(); if ($auth->get_user_id() == false) {
    return $this->action_login();
    } $controller_method = 'action_' . $resource; if (method_exists($this, $controller_method)) {
    return call_user_func_array(array($this, $controller_method), $args);
    }
    else
    {
    return $this->action_404();
    }
    } // Show login page
    public function action_login()
    {
    $this->template->title = 'Login';
    $this->template->content = View::forge('login', array());
    } // Show welcome page
    public function action_index()
    {
    $this->template->title = 'Home';
    $this->template->content = View::forge('index', array(
    'username' => Auth::get_screen_name(),
    ));
    } } My Auth Controller: <?php class Controller_Auth extends Controller_Rest
    {
    public function post_check()
    {
    $auth = Auth::instance(); $username = Input::post('username');
    $password = Input::post('password'); $redirect = Uri::create('/index'); if($auth->login($username, $password))
    {
    $this->response(array(
    'valid' => true,
    'redirect' => $redirect),
    200
    );
    }
    else
    {
    $this->response(array(
    'valid' => false,
    'error' => 'Invalid username or password, please try again'),
    200
    );
    }
    } } My login AJAX form JS: [removed] // Constants
    var LOGIN_AJAX_URL = '<?php echo Uri::create('auth/check'); ?>'; jQuery(document).ready(function($) { //
    LOGIN_AJAX
    $('#login-form').submit(function(event) { var username = $('#username').val();
    var password = $('#password').val(); if (!username || username == '')
    {
    alert('Please enter a username');
    }
    else if (!password || password == '')
    {
    alert('Please enter a password');
    }
    else
    {
    $('input[type=submit]', this).attr('disabled', 'disabled'); // Request Data
    var data = {
    username: username,
    password: password
    }; // Send Request
    $.ajax({
    url: LOGIN_AJAX_URL,
    dataType: 'json',
    type: 'post',
    data: data,
    success: function(data, textStatus, XMLHttpRequest)
    {
    // Returned from rest controller:
    // data.valid = true/false
    // data.redirect = the page we redirect to on successful login
    if (data.valid)
    {
    document.location.href = data.redirect;
    }
    else
    {
    $('#login-messages').html("Error: " + data.error);
    $('input[type=submit]').removeAttr('disabled');
    }
    },
    error: function(XMLHttpRequest, textStatus, errorThrown)
    {
    console.log(XMLHttpRequest.responseText);
    $('#login-messages').html(
    "textStatus: " + textStatus + " and errorThrown: " + errorThrown
    ); $('input[type=submit]').removeAttr('disabled');
    }
    }); $('#login-messages').html('Please wait, checking login...'); }
    return false;
    });
    }); [removed] When I click submit, upon the correct information being entered into the form, it just redirects back to the form. I know this is because of the $redirect variable, but I'm not sure how to do it correctly so it goes to index on successful login (I thought that my router checked this?)..
  • I've finally fixed the problem but the funny thing is, I have NO idea how / why! I changed the controller from Controller_Index to Controller_Start, changed the router to load the correct files and changed all the Uri::Create links, then changed them back again to Controller_Index and now it all works fine in Chrome. No idea. Thanks very much for the troubleshooting help though :)
  • Sorry, but I do not understood.
    1. Use Security class !!!
    2. Standard login form uses Controller_TEMPLATE
    3. Ajax login uses Controller or Controller_REST.
    Could you explain ones again what you want?
    You want to login with Ajax and "get" redirect to successful page?
    Redirect by Ajax or normal GET redirect?
  • I'm expecting my code, on successful login, to: > go to controller index
    > go through the router method
    > find that now I am logged in
    > NOT go to action_login() because Auth->get_user_id() returns TRUE
    > Instead go to action_index() I thought that's what my code should do, but the AJAX request is messing it up somewhere. Please advise?
  • J7mbo, sorry, my English is not good, therefore I do not understood what happen
    so,
    1. If you want to make auth thought POST form, you send $_POST AND $_POST
    I think you should use something without Template or REST.
    Because you are just check data. Pass and email - true or not.
    If yes, redirect to index page and set AUTH cookie.
    2. If you want to make ajax login, you should to make simple controller which reads data is true or not.
    If true, app sends by ajax cookies and javascript info to update some parts of code.
    <div id="menu_login"></div>
    Example: before ajax Menu : Sign in or Sign up. <div id="menu_login">Sign in ||| Sign up</div>
    After ajax: Menu: My profile, Settings, Messages, Logout. <div id="menu_login">My profile ||| Settings</div>
    Too complex logic in your code. Try to simplify.
    So difficult to make advance if I do not understand English. :) Sorry.
  • Well, I just want to know why it's not redirecting to index/action_index. Instead, it's redirecting to index/action_login again.
  • Debug your code. What is the value of 'data.redirect' before doing the location.href change?
  • It's [url=http://devserver2/tasks/public/index/index]http://devserver2/tasks/public/index/index[/url] It's going there. I was hoping it would go through the index controller and then to action_index (see the router() method), but it just still goes to action_login
  • What happens if you paste that URL in the browser? If that also goes to login, either your router code is not ok, or you are not seen as logged in, so you need to debug that.
  • Harro Verton wrote on Monday 2nd of July 2012:
    What happens if you paste that URL in the browser? If that also goes to login, either your router code is not ok, or you are not seen as logged in, so you need to debug that.

    It also goes to login. Doing an alert on data.authname in the AJAX success() function prints out Auth::get_screen_name() passed from the controller, so that's definitely working. It then does a [removed].replace(data.redirect) which = index/index, and loads the login screen. So it's something in the router code, and I'm not sure I know how to fix it. It's the ROUTER that's not detecting whether or not I'm actually logged in correctly.
  • On to the next possible victim then. What does $auth->get_user_id() return?
  • Harro Verton wrote on Monday 2nd of July 2012:
    On to the next possible victim then. What does $auth->get_user_id() return?

    So, the controller returns $auth->get_user_id to AJAX success: and the alert is: 'SimpleAuth, 1'. Then the page does the redirect to (what I assume is) the index controller, and still loads the action_login() instead of the action_index().
  • Ok, so it's not "false", so it should fall through there. Next question: what is $controller_method set to?
  • The $auth->get_user_id() is returned to the AJAX and console.logs out correctly in the JAVASCRIPT. However, when it then supposedly goes back to router(), straight after $auth = Auth::instance(); - I try var_dump($auth->get_user_id()); then die; and it prints out bool(false) - so I think it's between the AJAX and the router, because the router is never seeing a successful login.
  • What do you use for session storage? If a cookie, it might be that because of the fact that you do the redirect in the browser after the ajax request, you lose the updated cookie that the ajax call must produce. Can you see in your browser debugger that the session cookie is send back to the browser with the ajax response? And if so, does your browser store the cookie correctly (i.e. is your session and cookie config ok)?
  • I'm not too sure about this, but when looking at Session Storage & Cookies in chrome, after commenting out the redirect, nothing appears. So no cookie is being created? Also I haven't touched any session / cookie configs.
  • EDIT: IT WORKS IN FIREFOX NOT CHROME : ???? I've been trying to fix this for a week + , it just doesn't work in chrome, but it does in FireFox. Whattt!
  • Does it not work because the session cookie is not accepted? Modern browsers are more and more restrictive when accepting cookies which are not correctly configured or not RFC compliant. Chrome is pretty strict in this respect. That is why I asked you to debug the request/response, to see if the cookie is send back in the reponse header, and if so, to see if the browser actually stores it. If it's present but not stored, the browser has rejected it because of non-compliancy. For example, because you use [url=http://localhost/..]http://localhost/..[/url]. (according to the RFC, "localhost" is not a valid hostname).

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

In this Discussion