1

In my javascript I have some ajax requests $.getJSON({...}) for various actions. I have a php app that handles these ajax requests. Before processing the actual request, my app first checks the session and in the case the user hasn't logged in yet, it sends a refresh signal back. Something like:

if (not logged in) {
header('Refresh: 0;');
}
else {
//process request
}

But the client doesn't actually refresh. Is there something I'm missing when it comes to AJAX requests and the http refresh header?

paul smith
  • 1,327
  • 4
  • 17
  • 32

2 Answers2

4

AJAX requests don't affect the browser until told to do so. Meaning, if i fetch a page using AJAX, it gets returned, maybe stored in a variable and that's it. It does not do anything after that. You need to parse the return data and act accordingly.

In your case, you might rather return something like JSON, have the client side parse what the return data meant, and act accordingly.

i tend to do something like:

{
    "directives": {
        //contains directives what to do first before parsing the data
        "whatToDo" : "redirect" 
    },
    "payload" : {
        //actual page data
    }
}
Joseph
  • 117,725
  • 30
  • 181
  • 234
  • This isn't entirely the case. A download for example will occurr immediately if initiated by an ajax request without any further client processing necessary. The headers can alter behaviour of the client. – Endophage Apr 16 '12 at 05:42
  • @Endophage I was thinking the same exact thing. I'm curious if browsers have some list of headers that they do and don't ignore during AJAX requests? – paul smith Apr 16 '12 at 05:45
  • [this answer](http://stackoverflow.com/a/1534662/575527) pointed about redirects and used JSON instead of a hacky approach. – Joseph Apr 16 '12 at 05:46
0

So the file your calling in your request contains the header('Refresh: 0;'); ? Because that has no effect at all, what i would do is if the user is not logged in return an unique string like so:

if (not logged in) {
    echo "NOTLOGGEDIN";
}
else {
    //process request
}

and then in your AJAX request check if they are logged in:

$.get("someURL", function(data) {
    if(data == "NOTLOGGEDIN"){
        //Do something
    } else{
        //Display data
    }
});
Erik Terwan
  • 2,710
  • 19
  • 28