views:

26

answers:

2

SO I have a php function for redirecting

public function redirect($url, $permanent=false, $statusCode=303) {
    if(!headers_sent()) {
        header('location: '.$url, $permanent, $statusCode);
    } else {
        echo "<script>location.href='$url'</script>";
    }
    exit(0);
}

It's done me wonders so far, but Lets say that I am loading a tab via AJAX, which requires a user to be logged in. So ideally when the tab loads and it detects the user isn't logged in it redirects them to the index page. However, instead, the redirected page (http://localhost/something/index.php in my case) just loads inside the tab which makes sense, but is obviously not what I want to happen :)

However, is there a php solution to do this? Or should I just have a JavaScript redirect function at the root level that I call from the loaded AJAX tab if the user is not logged in?

Edit: Sorry. to clarify what I mean by tab, it's just HTML loaded into a DIV tag via AJAX

+1  A: 

Your question isn't totally clear in regards to what you mean by "tab"

Maybe it would work for you to use

top.location.href='$url'
jayrdub
Thanks a lot. At first this didn't appear to work for me as it seems to work more like this.top.location.href='$url', however when i typed window.top.location.href='$url' it worked fine! Thanks
KennyCason
+1  A: 

you can try

php function

public function redirect($url, $permanent=false, $statusCode=303) {

    if($_SERVER['HTTP_X_REQUESTED_WITH'] === "XMLHttpRequest"){
    die("AjaxRequest");
    }
    else{
        if(!headers_sent()) {
            header('location: '.$url, $permanent, $statusCode);
        } else {
            echo "<script>location.href='$url'</script>";
        }
        exit(0);
    }
    }

Javascript function

function ajaxresponse()
{
var response = //your ajax request response

if(response == 'AjaxRequest')
{
location.reload();
}
}

Explaination: First Check in php whether it is ajax request or not. so for redirection, send response from php as ajax session so that u can check out this response in javascript for which redirection will not take place.

after detecting this response in javascript you can redirect to index page from your javascript function.

Hope this helps

Yogesh
This seems to be the way to go for my particular setup. I'll check it out when I get home tonight. thanks,
KennyCason
I ended up getting the above example to work and I ended up mixing your answers by replacing `die("AjaxRequest");` with `echo "<script>window.top.location.href='$url'</script>";` Since sometimes when a "tab" is loading via AJAX and the headers() haven't been set I still want it to redirect at the top level. Thanks again!
KennyCason
I hope my random babbling made sense. :)
KennyCason