Before I get any down-marking, please bear in mind that I'm relatively new to this whole web application development thing, so please go easy on me! My problem is that i can not seem to bind the bootstrap "switch" to a js function that sends an AJAX request, to update a record in the database.
here's my attempt:
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-switch/3.3.4/js/bootstrap-switch.js" data-turbolinks-track="true"></script>
<script>
$(document).ready(function(e){
var stopchange = false;
$('.switch-input').on('switchChange.bootstrapSwitch', function (e, state) {
var obj = $(this);
var arr = e.split("_");
var appid = arr[1];
var owaspid = arr[2];
if(stopchange === false){
$.ajax({
method: 'POST',
url: 'actions.php',
data: {
val: value,
user: '<?php echo $_SESSION['user'] ?>',
app: appid,
owasp: owasp,
action: "update_worklog"
},
success: function(result) {
if(result['done'] == true) {
alert('Status changed successfully.');
} else {
alert('Error:'+result['message']);
if(stopchange === false){
stopchange = true;
obj.bootstrapSwitch('toggleState');
stopchange = false;
}
}
},
error: function(result) {
alert('Error! Unable to update progress.');
if(stopchange === false){
stopchange = true;
obj.bootstrapSwitch('toggleState');
stopchange = false;
}
}
});
}
});
});
</script>
</head>
Note: The $v->checked statement derives from a json that is parsed beforehand
echo '<td><label class="switch switch-text switch-primary"><input id="check_' . $SomeID. '_' . $v->name . '" name="ncheck_' . $SomeID . '_' . $v->name . '" type="checkbox" class="switch-input"';
if($v->checked == "True") {
echo "checked";
}
echo '><span data-on="✓" data-off="×" class="switch-label"></span> <span class="switch-handle"></span></label></td>';
for the record: i've been through a lot of the similar issues in stackoverflow (such as : this or this or this ) but i just can't seem to get this thing to work properly. if you have any comments/ideas/possible solutions, please don't hold back
</div>
I too have came across such issue.I think this should solve your problem
$("input.switch-input").on('change.bootstrapSwitch', function(e){
if($(this).is(':checked'))
alert('checked');
else
alert('not checked');
//code..
$.ajax({
//code..
success: function(result) {
if(result['done'] == true) {
alert('Status changed successfully.');
} else {
alert('Error:'+result['message']);
if(stopchange === false){
stopchange = true;
$(this).bootstrapSwitch('toggleState');
stopchange = false;
}
}
},
error: function(result) {
alert('Error! Unable to update progress.');
if(stopchange === false){
stopchange = true;
$(this).bootstrapSwitch('toggleState');
stopchange = false;
}
}
});
});