The correct way to redirect in PHP and Ajax is called PHP?

So now I am using something like this to redirect users in PHP:

//This is a simplified version, but demonstrates it use.
function redirect($location) {
    header("Location: $location");


The use case redirects the user to the login page if their session has expired, or if they try to do something that requires them to login, it sends them to a 404 page.

So, in PHP, I can just type:



My problem is that I now use a lot of PHP called via Ajax for things like form processing and content updating; and this approach for redirection does not work when called via Ajax.

I was planning to just change this function to use Javascript and not PHP.

So, I would use something like this:

function redirect($location) {
    echo '<script>';
        echo 'window.location.replace("'.$location.'");';
    echo '</script>';


Which, as far as I know, will work for both normal PHP usage and Ajax for PHP.

Is this bad practice? Currently, using this only for Ajax calls causes a lot of code overhead, so it makes sense to just use it for everything.

Clarify; I'm looking for a solution that will work in both regular PHP and PHP Ajax calls, so I can use the same code for both - instead of doing it in isolation. For example, when submitting a form action="dosomething.php"

, depending on the situation, this file can simply add a line to the database or redirect to a specific page. But this can be called either using Ajax or a normal HTML form action.


source to share

1 answer

I would create a generic AJAX function in your Javascript that makes all the ajax calls. Then, in that global function, you would add a check if the return value is -1 or whatever and do a javascript redirect.

Example JS function (if you are using JQuery):

function ajaxCall(url, data, requestType, ...) {
       type: requestType,
       url: url,
       data: data,
       dataType: 'json',
       success: function(result) {
           if (result.Status == 'Redirect') {
               window.location = result.RedirectLink;


Then use the above js function ajaxCall()

for all your ajax calls.

Then, in your PHP, you will return something like this:

echo json_encode(array('Status' => 'Redirect', 'RedirectLink' => '/'));


The above approach is easier to change later if something changes.



All Articles