Reputation: 21
OK here's what I've got. I have this voting system where you click a button and it sends a text field to a php script using ajaxrequest.open(). After it sends the data to the php script I want it to load a new page. Here's what I have (condensed version)
var mytext = document.getElementById('textfield').value;
ajaxRequest.open("GET", "vote.php?mytext="+mytext, true);
ajaxRequest.send(null);
window.location.href = "thanksforvoting.htm";
So it sends the text field to vote.php - which works only if i take out the window.location.href line. As long as that line is in, it won't do the ajaxrequest. I assume maybe it's cancelling out because it's loading another page.
I thought maybe I could just use a php 'header' command but that doesn't seem to work. It's not taking me to the page. The script above takes me to the page, but it doesn't get to the php script. If I take out the window.location.href the php script runs but it obviously doesn't take me to the page.
Upvotes: 0
Views: 1017
Reputation: 33865
Since ajax request are made asynchronously, you need to use a callback, otherwise the redirect will occur before the request is complete. In your case, it would be something like this:
var mytext = document.getElementById('textfield').value;
ajaxRequest.onreadystatechange = callback;
ajaxRequest.open("GET", "vote.php?mytext=" + encodeURIComponent(mytext), true);
ajaxRequest.send(null);
function callback() {
if (ajaxRequest.readyState === 4 && ajaxRequest.status === 200) {
window.location.href = "thanksforvoting.htm";
}
}
MDN has a good getting started guide on Ajax.
Upvotes: 1