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?
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?
Share Improve this question edited Nov 5, 2015 at 16:54 11mb 1,3592 gold badges17 silver badges33 bronze badges asked Oct 26, 2015 at 20:22 John DownJohn Down 5202 gold badges6 silver badges20 bronze badges 2- It is asynchronous. The browser is redirected before the result it back. – Rik Commented Oct 26, 2015 at 20:23
- If you're doing the XHR in order to make something happen at the server, you really should do a POST and not a GET to avoid a very simple CSRF vulnerability. – Pointy Commented Oct 26, 2015 at 20:24
1 Answer
Reset to default 13The requests are asynchronous that means window.location will not wait for the request to plete 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 plete 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 pleted we can move away
window.location = "index.html";
}
}
posts.open("GET", api+user+"/"+password+"/"+id+"/"+latitude, true);
posts.send();