I want a checkbox on a web page. When I click it, it sends an ajax request to the server. When the server replies, I want the checkbox to change. I can fix everything except the fact that the checkbox immediately changes state when clicked.
Add to your onclick "return false;" and it should not change.
Are you sure you really want this? An Ajax-Request can take its time. When the user gets no feedback, they may be inclined to click again and again, until something happens. When this deactivates the button (again after some time) the user gets even more puzzled.
Rather think about providing immediate feedback (e.g. check the box) and display an indicator next to it, that signals communication with the server (e.g. the famous spinning wheel). When the result is back, hide the indicator and deactivate the checkbox if needed. You may also want to inhibit posting the form during the ajax request.
You could start your onchange method with checkbox.checked=NOT checkbox.checked
(you may have to modify this for your language of choice), you'll probably get a flicker but it should put it back quickly enough.
I think you should use other approach indeed. Maybe a button/image button because you want to fire some actions for a click to represent a specific command (desire) from the user. I will try to explain better: i think you have some info in the page and some gadgets where the user can click and do something (add an item to a cart) and i think it is more usable if the gadget has more visual appeal to the user than a checkbox (i.e. a "add it" for instance).
Hope this help.
You could probably do something like this: when the checkbox is clicked, set the checkbox to "disabled" (this greys out the checkbox and makes it uneditable), make your ajax call, and once you get the ajax return remove the "disabled" from the checkbox. Something like this (using jQuery, untested):
$('#mycheckbox').click( function() {
var checkbox = this;
$(checkbox).attr('disabled','1');
$.post( url, data, function() {
// if successful
$(checkbox).removeAttr('disabled');
}
}
<input id="theChkbox" type="checkbox" onclick="this.checked=!this.checked;sendAjaxRequest(this);">
this.checked=!this.checked
will reset the state of the checkbox to what it was before it was clicked. This should work in all browsers without the state flickering (too much).
sendAjaxRequest()
will do your magic and when the request comes back set the appropriate checked state of the checkbox. Passing this
to sendAjaxRequest()
should give you a reference to the checkbox so you can adjust its state. Failing that, just use document.getElementById("theChkbox")
to retrieve a reference to it to set its state.