phpjavascriptcodeigniterxmlhttprequesttankauth

Handling php redirect in ajax call when codeigniter/tank auth session timeout reached


Hey all I have a javascript function within a codeigniter view that retrieves some information from a codeigniter controller function that is acting strangely when the timeout for a user's session is reached. Within the called php function I have a statement that looks like this:

  if (!$this->tank_auth->is_logged_in()) {
  redirect(site_url('login'));}

This redirects them to my login page if they are not logged in. However in the javascript function I take the response text and set the contents of a div equal to it.

  xmlhttp = new XMLHttpRequest();
  xmlhttp.open("POST", "mycontroller/myfunction/", false);
  xmlhttp.send();
  document.getElementById("mydiv").innerHTML=xmlhttp.responseText;

If the user is logged out when they call this function it will return the login page's responseText and insert it into the div instead of redirecting to the login page. This looks terrible. How can I stop it from doing this if the user session times out while looking at this page? I cannot change the timeout limit because other applications rely upon it.

Really this is not a codeigniter or tank_auth problem at all, simply how to redirect from a php function that is being called in an ajax request instead when I am originally using that function to generate a string for the responseText.


Solution

  • You need to parse the response and determine whether it is the type of response you're expecting. If you're expecting under a certain number of characters, you can check length, but that might not be as reliable as checking for specific dom objects or strings.

    You could do, for example:

    if(xmlhttp.responseText.length < 200) {
        document.getElementById("mydiv").innerHTML=xmlhttp.responseText;
    } else { 
        window.location.href = 'some url';
    }
    

    Another alternative would be to use CodeIgniter's AJAX response check to do something else instead of loading the view (or load a different view):

    if ($this->input->is_ajax_request())
    {
        // do something else 
    }
    else
    {
        // do what you were doing before
    }
    

    Hope this helps! I would shy away from doing the PHP/CI method because it sounds like you would be adding exceptions everywhere in your code which would not be pretty. It's totally up to you, though.