I have a jQuery change event on a checkbox that makes an Ajax call, and then highlights the table row that the checkbox belongs to. I’m having a problem when the Ajax call reports an error – in this case I want to reverse the checkbox click (I’m using that.prop("checked", !that.prop("checked")) to do so). However, what is happening is that it enters an infinite loop of calling the change event. As you can see, in order to stop this behaviour I’ve tried to set a variable called ajaxInProgress, but it doesn’t seem to be working as I’d hoped. Can anyone provide an alternative approach or spot the bug? I’m not sure that the way I’m resetting the checkbox is necessary – is it possible to reset the checkbox and still prevent the change event from kicking off?
var ajaxInProgress = false; //add this to stop recursive calls when errors occur
jQuery(document).ready(function() {
jQuery(".cc").change(function (e) {
if (ajaxInProgress) return;
var mode = "remove"
if (jQuery(this).attr("checked")) {
mode = "add"
}
//grab the application ID from the checkbox ID
var thisApp = this.id.substr(3);
var that = jQuery(this);
ajaxInProgress = true;
jQuery.get("/particular/edit-ajax", { application_id: thisApp,
party_id: 1920,
party_rel_id: 21,
mode: mode} , function(response) {
if (response == 0) {
that.closest('tr').removeClass('even').removeClass('odd').addClass('highlight');//highlight the tr
} else {
e.preventDefault();
that.prop("checked", !that.prop("checked")); //reset the checkbox if there was an error
alert("Please contact support - couldn't update database for application "+thisApp+". Response was: "+response);
}
});
ajaxInProgress = false;
});
});
It may be because you have
ajaxInProgress = false;after youjQuery.get. This sets it tofalsebefore you even get anything back from your ajax request. Move that line to inside the callback:Fiddle: http://jsfiddle.net/gromer/BgNfR/
My Fiddle is using
window.setTimeoutto simulate the ajax call. I thought my solution wasn’t working, but it was because I initially usedwindow.setIntervalso it looked like it was getting called over and over again, which it was, just wasn’t simulating the ajax request as I should have been.