Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript XMLHttpRequest() and Redirect

I want to send a XMLRequest to server and then redirect user to front page so far I have:

var posts = new XMLHttpRequest();
var api="XXXXXXXXXX";
posts.open("GET", api+user+"/"+password+"/"+id+"/"+latitude, true);
posts.send();

window.location = "index.html"

If I only run the code without the redirect at the end it works great but if I have a the redirect the API GET request fails. Can someone explain to me what I'm missing?

like image 476
John Down Avatar asked Jun 23 '26 13:06

John Down


1 Answers

The requests are asynchronous that means window.location will not wait for the request to complete before executing. That results in navigating away from the current page and the browser canceling the request.

To fix this you have to wait for the request to complete before navigating away. You can do this by listening to the state changes of the request.

var posts = new XMLHttpRequest();
posts.onreadystatechange = function() { // listen for state changes
  if (posts.readyState == 4 && posts.status == 200) { // when completed we can move away
    window.location = "index.html";
  }
}
posts.open("GET", api+user+"/"+password+"/"+id+"/"+latitude, true);
posts.send();
like image 146
toskv Avatar answered Jun 26 '26 03:06

toskv