0

I am trying to achieve the following. After a form is submitted successfully I want to run a code after the server response is 302. for this example, I have a form that is waiting to be submitted, after a successful submission the server returns a 302 response. I am trying to listen to this response so I can run a code snippet after the 302 response. This is what I have done so far:

var posts = new XMLHttpRequest();
  posts.onreadystatechange = function() {
    if (posts.status == 302) { 
      alert("succesfull")
    }
  }
  posts.open("POST", "http://127.0.0.1:8000/", true);
  posts.send();

This does not work, can someone explain why?

  • Does this answer your question? [Prevent redirection of Xmlhttprequest](https://stackoverflow.com/questions/228225/prevent-redirection-of-xmlhttprequest) – Christopher Dec 08 '21 at 10:37

1 Answers1

0

you are missing readyState in if condition which holds the status of the XMLHttpRequest.

try to modify your code like below:-

function loadDoc() {
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            alert('passed!')
       }
    };
    xhttp.open("POST", "http://127.0.0.1:8000/", true);
    xhttp.send();
}

readyState 4 means request finished and response is ready.

Manish Kumar
  • 595
  • 2
  • 15
  • They question is asking how to detect a `302` status so (a) Testing for `200` is **not what they want!** and (b) they only need to wait for the status, there is no reason to wait until the entire response body has been processed so waiting for `readyState` to be `4` is pointless. – Quentin Dec 08 '21 at 10:41
  • Still doesnt catch the server response :/ –  Dec 08 '21 at 10:45