Reputation: 5128
I have a page with several different forms on which people can insert their zipcode and housenumber. After an onblur
on these input field I make an ajax call to get the streetname and city from the server based on the zipcode and housenumber.
function getAddress(postcode, streetnum, form, tr) {
$.ajax({
type: "GET",
url: "some url with streetnumber and zipcode",
dataType: "json",
success: function(data){
var street = $("input.formstreet", tr);
var city = $("input.formcity", tr);
street.val(data.data[0].streetname);
city.val(data.data[0].city);
tr.css("visibility","visible");
switch(tr.get(0).nodeName.toLowerCase()){
case "tr":
tr.css('display','table-row');
break;
case "tbody":
tr.css('display','table-row-group');
break;
default:
tr.css('display','block');
};
}
});
}
This works as it should, however if the page gets reloaded and the field are already filled in the address needs to get reloaded from the server.
$("#thing").keyup(function(){
completeAddress1();
});
completeAddress1();
$("#something").keyup(function(){
completeAddress2();
});
completeAddress2();
$("#something else").keyup(function(){
completeAddress3();
});
completeAddress3();
$("#some other thing").keyup(function(){
completeAddress4();
});
completeAddress4();
The completeAddress()
functions just check whether a ajax call is needed, if so it calls getAddress.
So... to the actual problem... At pageload several ajax calls are made, and only the last one called returns(I checked with fiddler), now I get why only one returns but what can I do about it...
Upvotes: 2
Views: 1400
Reputation: 5128
Fixed it by checking if there is already an xhr
running, if so, append a callback function to an array. When the first xhr
is done, it checks the array to see if there are any functions and tries to execute the first one, each function does this recursively until the array is empty.
basically something like this:
var arr = [],
xhr;
function applyXhr(func){
if(xhr){
func()
}else{
arr.push(func);
}
}
applyXhr(function(){
xhr = $.ajax({
//stuff,
complete:function(){
//other stuff
if(arr.lenght){
arr.shift()();
}
}
});
})
Upvotes: 3
Reputation: 981
<form name="form1" id="form1" method="post" autocomplete="off"
action="http://www.example.com/form.cgi">
[...]
</form>
Upvotes: 1