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?

1

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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.
Still doesnt catch the server response :/