Redirect parent page from loaded AJAX tab

SO I have a php function to redirect

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);
}

Until now, this has done me miracles, but I will say that I am loading the tab through AJAX, which requires the user to be logged in. Therefore, ideally, when a tab is loaded and it is discovered that the user has not 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 obviously not what I want :)

However, is there a php solution for this? Or do I need to 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, this is just HTML loaded in a div tag via AJAX

+3
source share
2 answers

Your question is not entirely clear regarding what you mean by “tab”

You might find it helpful to use

top.location.href='$url'
+3
source

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 if this is an ajax request or not. so for the redirect, send the response from php as an ajax session so that you can check this answer in javascript for which the redirect will not take place.

javascript javascript.

,

+1

Source: https://habr.com/ru/post/1764630/


All Articles