I’ve got a simple checkbox that is either checked on or off by querying the database. A user can change this value and I send a request via ajax. The url is wacky because it is a Joomla component (not important for this question, but just in case).
$(function() {
$("#iButton").iButton();
$('#iButton').change(function() {
var checkedLength = $(this + ':checked').length;
if(1 == checkedLength){
$.ajax({
url: 'index.php?option=com_mycomponent&task=globaldetection&id_hash=<?php echo $id_hash; ?>&global_monitoring='+checkedLength+'&format=raw'
});
} else {
$.ajax({
url: 'index.php?option=com_mycomponent&task=globaldetection&id_hash=<?php echo $id_hash; ?>&global_monitoring='+checkedLength+'&format=raw'
});
}
});
});
<?php
//highlight whether the checkbox is on or off
if ($userstatus == "ENABLED") //get this value from server
{
//turned on
$global_monitoring = "checked=\"checked\"";
}
else
{
$global_monitoring = "";
}
?>
<div class="dropshadow">
<p id="iButtontext">
<input type="checkbox" id="iButton" <?php echo $global_monitoring; ?> name="iButton_checkbox" />
</p>
</div>
This works fine and as I expect but I have several questions here:
- I duplicate the
ajaxfunction twice depending on the condition. Is there a better way to do this or completely acceptable? - I’m only passing in url and no other settings. I’ve always used the
successsetting but in this case there is no other response I need to do. I know it is optional but should I be doing something else at that point? - Any other settings I should be passing into ajax? It just seems too…simple.
Any guidance is appreciated. Thanks.
You don’t need the if/else structure at all, because in both branches you have an identical line of code so if you just put that line of code on its own it would work (it would still use the value of
checkedLength).However,
$(this + ':checked').lengthdoesn’t make sense – your selector concatenates the string':checked'to the end of the objectthis. I don’t see how that could be working at the moment. An equivalent way to get the result as a “length” would be$(this).filter(':checked').length, which is kind of clunky. Or you can test it as a boolean withif ($(this).is(':checked')), except even that is way more complicated than it needs to be whenthis.checkeddoes the same job.Given that you can get the checked state directly with
this.checkedI think the following is simpler (and definitely more efficient):(I’m assuming the
.lengthyou were originally using could only ever be0or1since the event is on an element that you select by id.)No. If you don’t need to do anything on success then don’t specify a success callback – it may be wise to specify an error callback though, in case the call doesn’t work for some reason.