Reputation: 161
I was experiencing APIs and found myself block on something.
I have thet Jquery function that fetch data from an api, and in order to not get a "reposition" effect, I need the function to wait for all the call to be made before triggering another function that will places all the api date in place.
I tried using AjaxStart and AjaxStop, but while the first one works perfectly, the second one doesn't, and I can't figure out why...
The app i'm building is quite big, So I made a codePen to simplify my question :
HTML:
<div id="button"></div>
<div id='locationbox'>
<span id='city'>Get the country</span>
<img id = "countryimg" src="">
<div id='searching'> searching...</div>
</div>
CSS
#button{
height : 150px;
width : 150px;
border : 5px solid black;
border-radius : 50%;
position : absolute;
top : 45%;
left : 45%;
}
#locationbox{
text-align : center;
width : 300px;
position : absolute;
top : 25%;
left : 38.5%;
}
JavaScript :
$("#button").on('click',function(){
getCity();
});
$(document).ajaxStart(function() {
$("#city").html("fetching data");
});
$(document).ajaxStop(function() {
$("#searching").html("Success")
});
function getCity(){
$.ajax({
datatype : "json",
contentType : "application/json",
type : "GET",
url : "https://nominatim.openstreetmap.org/reverse?",
data : {
format:"json",
lat :"50.8503",
lon : "4.3517",
zoom:"18",
adressdetails:"1"
},
success : function(quote){
var city = quote.address.city;
var country = quote.address.country
var countryCode = quote.address.country_code.toUpperCase()
document.getElementById("city").innerHTML = city + " , " + country;
document.getElementById("countryimg").src = "http://www.geognos.com/api/en/countries/flag/" + countryCode + ".png";
document.getElementById("country").innerHTML = country;
},
error : document.getElementById("city").innerHTML = "error!"
});
};
As you can see in this code pen while the AjaxStart triggers, the AjaxStop won't. Thanks for reading and thanks you all for helping me.
Upvotes: 1
Views: 1261
Reputation: 2832
This is happening because of an error in your success code block. Because of this error, your ajaxStop does not execute.
Remove the line document.getElementById("country").innerHTML = country;
since there is no element in the document with that id. Else, add an element with id country
Check the working codepen https://codepen.io/anon/pen/NyjMOQ
Upvotes: 2