Reputation: 71
I am creating a login form and I need to redirect the user to his/her profile page! I am using AJAX Requests so header redirect is not working at all. It just stays on the homepage.
So how can I redirect the user to another page in pure javascript PHP ajax call? Please give the answer in pure javascript. I don't like to use jQuery at all!
Javascript:
function ajaxCall(){
var xhttp;
if(window.XMLHttpRequest){
xhttp = new XMLHttpRequest();
}
xhttp.onreadystatechange = function(){
if(this.readyState === 4 && this.status === 200){
document.getElementById('error').innerHTML = this.responseText;
}
};
var parameters = 'email='+document.getElementById('email')+'&password='+document.getElementById('password');
xhttp.open('POST', 'login.php', true);
xhttp.setRequestHeader('Content-type', 'application/x-www/form/urlencoded');
xhttp.send(parameters);
}
Login.php(PHP)
<?php
if(isset($_POST['email']) && isset($_POST['password'])){
$ema = $_POST['email'];
$pass = $_POST['password'];
if(!empty($ema) && !empty($pass)){
if($ema === 'Bill' && $pass === 'Cool'){
header('Location: https://www.google.com');
}
}
}
Upvotes: 2
Views: 8882
Reputation: 1044
Make an ajax call.
<?php
header('Content-Type: application/json');
echo json_encode(['location'=>'/user/profile/']);
exit;
?>
The ajax response will return something like
{'location':'/user/profile/'}
In your ajax success javascript function
xhr.onreadystatechange = function () {
if (xhr.status >= 200 && xhr.status <= 299)
{
var response = JSON.parse(xhr.responseText);
if(response.location){
window.location.href = response.location;
}
}
}
Upvotes: 3
Reputation: 527
I landed here looking for an Ajax solution, nevertheless MontrealDevOne's answer provided useful. If anyone else is curious about the ajax method too, here you go:
$('body').on('submit', '#form_register', function (e) {
var form = $(this);
$.ajax({
type: 'POST',
url: 'form_submissions.php',
data: form.serialize() + "&submit",
dataType:"json",
success: function (data) {
if(data.location){
window.location.href = data.location;
}
},
error: function(data) {
alert("Error!");
}
});
e.preventDefault();
});
Just my 2 cents, hope it helps :)
Upvotes: 1
Reputation: 367
try this bill if its works.
window.location.replace("http://www.google.com");
Upvotes: 0