I’ve written a js function that asynchronously contacts the server via a php query to a table that looks like:
function grabber(url, element)
{
async = new XMLHttpRequest();
async.onreadystatechange=function()
{
if (async.readyState==4 && async.status==200)
{
document.getElementById(element).innerHTML=async.responseText;
}
}
async.open("GET", url, true);
async.send();
}
Then, I have another function that when the event handler for an element gets fired, it calls this function twice with different parameters to fetch two data streams for two currently empty elements. The thing that confuses me is that both of them can’t work at the same time. They both work when they are the only method in the function, but when both of them together, only one of them works. Order doesn’t matter.
$('.box').keyup(function() {
grabber("herp.php?q=" + $(this).val(), "rice");
//grabber("derp.php?q=" + $(this).val(), "gohan");
});
derp seems to take precedence regardless of the position, and herp only works when derp is commented out.
The php files only output regular html elements and work fine individually. Any ideas on how to get these to work simultaneously?
You are creating global variables when you need to create local variables:
This has the effect that when the
grabberis called multiple times, each of the calls overwrites the previous value ofasyncwith the new request. This in turn means that when each of your callbacks finally executes, it’s using the result from the last value ofasync— which causes all target elements to get the sameinnerHtml.To correct the problem, add
varin front: