Redirecting to a new page based on an AJAX call
I am using ajax with jQuery to make a request from a page on my site. Now if the login failed (or the call failed for a different reason), I return an error message and put it in a label. But if the call succeeds, I want to navigate to another page. My issue is that if the call succeeds, I end up with the text of the new page in my label.
Here's my Javascript:
$.post("chklogin.php", { username: username, password: password }, function(data) {
$('#msg').html(data);
});
And here's the PHP that it calls:
if(mysql_num_rows($result)==0) {
$msg="<h3>Enter val开发者_开发问答id Username and Password.</h3>";
echo $msg;
} else {
$row=mysql_fetch_assoc($result);
$_SESSION["userid"]=$row["pgmail"];
header("location:user.php");
}
Well this issue could have been clearer, and I would encourage you to check your spelling and code before you post again.
The issue is that you haven't sent the page to redirect, you have sent the page being called to redirect.
To fix this issue:
Firstly, get rid of the header redirect on your PHP code and replace with:
echo 'SUCCESS';
Secondly, change your AJAX code to the following:
$.post("chklogin.php", { username: username, password: password }, function(data) {
if(data=='SUCCESS'){
window.location.href = "user.php";
}else{
$('#msg').html(data);
}
});
This will make the page redirect, not the page called by AJAX.
精彩评论