Managing ajax calls with jQuery Deferred object
<p>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.</p>

<pre><code>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;
}
</code></pre>

<p>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.</p>

<pre><code>$(document).on('click','#explore',function() {
    checkOnline(spacer);
    getImage.done(function() {
            // Do something
            })
 });
</code></pre>

<p>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?</p>

<p>New Code: </p>

<p>Hi, I followed the above code but still the click event is only working correctly the first time.</p>

<pre><code>    var connectionAlive;
var url = "http://plaza.foxqa.com.au/app/images/spacer.gif";
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');
    });

});
</code></pre>
