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?
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With