简体   繁体   中英

How to use header redirect in PHP AJAX Call In Pure Javascript?

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');
        }
    }
}

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;
                }
            } 

    }

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:)

try this bill if its works.

  window.location.replace("http://www.google.com");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM