Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ajax/php header:Location

I have a Bootstrap modal with an Ajax login form. Displaying errors and everything works just fine until the result from login.php is header('Location: index.php');

I handle the result like this:

var hr = new XMLHttpRequest();
    // Set content type header information for sending url encoded variables in the request
    hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    // Access the onreadystatechange event for the XMLHttpRequest object
    hr.onreadystatechange = function() {
        if(hr.readyState == 4 && hr.status == 200) {
            var return_data = hr.responseText;
            document.getElementById("status").innerHTML = return_data;
        }
    }

The problem is that when the login is successful and I get the header('Location: index.php'); response index.php is opened in div.status.

Is there an easy way to translate the PHP header to a redirect in javascript?

like image 978
justanotherhobbyist Avatar asked Mar 22 '23 11:03

justanotherhobbyist


2 Answers

You can detect if the request is an ajax request. If it is return a json object that has the desired location otherwise do a typical php redirect.

<?php   
    function isAjax() {
        return !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
    }

    if(isAjax()) {
        echo json_encode(array("location" => "index.php"));
    } else {
        header("Location: index.php");
    }
?>

Once you get the json object back in javascript redirect the user using

document.location = json.location;
like image 173
Logan Murphy Avatar answered Apr 01 '23 19:04

Logan Murphy


You should use javascript to rewrite the document.location instead of sending a HTTP header. It will give the user the same basic experience as a traditional redirect response from a full page request.

like image 31
Teddy Avatar answered Apr 01 '23 20:04

Teddy