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?
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;
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With