I have to check the availability of internet access in a device at a given point of time. So, I am making an ajax call to the server to load a tiny image. I came across jQuery Deferred and tried to use it.
var spacer = "some url";
var getImage;
var connectionAlive;
function checkOnline(spacer) {
getImage = $.ajax({url:spacer})
.done(function() {console.log('Connection alive');connectionAlive = true;})
.fail(function() {console.log('Connection dead');connectionAlive = false;});
if(connectionAlive === true) {
return true;
}
return false;
}
Now i have to call this checkOnline function when certain events occur. So, i am calling the function and waiting till the promise is resolved.
$(document).on('click','#explore',function() {
checkOnline(spacer);
getImage.done(function() {
// Do something
})
});
This only works the first time and I think it is because the deferred object state stays the same once it is resolved. How should I write my code so that i can actually check the connection every-time the click event fires?
New Code:
Hi, I followed the above code but still the click event is only working correctly the first time.
var connectionAlive;
var url = "http://example.com";
function checkOnline(url, callback1,callback2) {
$.ajax({url:url})
.done(function() {console.log('Connection alive');connectionAlive = true;})
.done(callback1)
.fail(function() {console.log('Connection dead');connectionAlive = false;})
.fail(callback2);
}
$(document).on('click','#explore',function() {
checkOnline(url, function(){
console.log('Connection Alive from event');
},function() {
console.log('Connection Dead from event');
});
});