Force redirect after Jquery AJAX Call from PHP

http-redirect, jquery, php

Solution

Your Javascript redirect needs script tags. Try this:

public function redirect($url = SITE_URL, $isAjax = false) {
    if ($isAjax === true) {
        //its ajax call, echo js redirect
        echo '<script>window.location = ' . $url . ';</script>';
    } else {
        header("Location: {$url}");
    }
    exit;
}

In terms of handling this within your ajax, assuming jQuery

$.ajax(
    {
        type: "POST",
        url: url,
        data: postParams,
        success: function(data)
        {
            //do something with success response
        },
        error : function(httpObj, txtStatus)
        {
            if(httpObj.status == 401)
            {//redirect to login
                var loginUrl = '/login';
                document.location.href = loginUrl;
            }
            else if(httpObj.status == ...)  //etc
            {//do something

            }
            else
            {
                alert("Ajax\n Error: " + txtStatus + "\n HTTP Status: " + httpObj.status);
            }
        }

Problem

I have a custom framework and I detect if a request is an ajax in my Request file. In my basecontroller I check if user is logged in: ``` If user is not logged in: 1. if request is ajax - force JS redirect from PHP (unable to do) 2. if request is not ajax - PHP redirect (header, works) ``` I cant get number 1 to work. Here is my redirect code: ``` //User::Redirect public function redirect($url = SITE_URL, $isAjax = false) { if ($isAjax === true) { //its ajax call, echo js redirect echo '<script>window.location = ' . $url . ';</script>'; } else { header("Location: {$url}"); } exit; } ``` Code for login check: ``` //Basecontroller::__construct if ( ! $this->user->isLoggedIn()) { //redirect to login page $this->user->redirect('/login', $request->ajax()); exit; } ``` But instead of redirecting on ajax calls it just outputs `<script>window.location = URL</script>` NOTE: I know i could add check on each of my AJAX call to do redirect from there but Im trying to avoid that and let my PHP script detect in base controller and redirect rather than me adding check to all of my AJAX calls (alot).

Original source