Alamgir Khan Alamgir Khan - 25 days ago 6
Javascript Question

How i use move to another page after successful validation of form using XMLHttpRequest because Header function is not wroking with ajax

Javascript:

var xhttp = new XMLHttpRequest();

xhttp.onreadystatechange = function(){
if(xhttp.readyState==4 && xhttp.status==200){
document.getElementById("display_result").innerHTML=xhttp.responseText;
}
};
document.getElementById('loading').style.display='block';
xhttp.open("POST", "users_process.php", true);

xhttp.setRequestHeader('X-Alt-Referer', 'dashboard.php');
xhttp.send(data);


PHP:

<?php
$execute_query=$data_access->Execute($query);
if($execute_query==true){
header("location: dashboard.php");
}else{
echo("<div id='error'>Some error occured during uploading Please try again</div>");
}
?>

Answer

XMLHttpRequest returns a DOMString that contains the response to the request as text, or null if the request was unsuccessful or has not yet been sent.

So when you redirect on the serverside, you don't redirect on the client side; the request just returns whatever is echoed on the server side as response. What you can do is return a value (a string or a boolean) assuring that the query was OK. Then, on the client side, you can check for that value and perform a redirect using window.location.href.