Reputation: 12328
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
Upvotes: 3
Views: 4157
Reputation: 4075
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
Upvotes: 1
Reputation: 24368
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'
Upvotes: 3