My goal is from a Bootstrap toggle button write on MySQL DB “yes” or “no”. I know that JavaScript in client-side so I found a way (but not sure is the best) to collect variable from JavaScript and pass it to a PHP file that will write on DB. My relevant code is below, but if I try, nothing happens. I suppose that inside my JavaScript code I have to call “function saveStato”, but I cannot understand in which way.
$(function() { $('.inServizio').change(function() { if($(this).prop('checked')){ console.log('TEST_ON') function saveStato() { $.post("inServizio.php", { stato: $("SI").val(), }, function(data,status){ document.getElementById("saveWarningText").innerHTML = data; $( "#saveWarningText" ).fadeIn(100); setTimeout(function(){ $( "#saveWarningText" ).fadeOut(100); }, 3000); }); } } else { console.log('TEST_OFF') } //$(this).prop('checked') }) });
Advertisement
Answer
You can define it outside of your change listener, and call it inside with
saveStato();
Or just get rid of the function altogether and just have
$('.inServizio').change(function() { if($(this).prop('checked')){ console.log('TEST_ON') $.post("inServizio.php",{stato: $("SI").val()},function(data,status){ document.getElementById("saveWarningText").innerHTML = data; $( "#saveWarningText" ).fadeIn(100); setTimeout(function(){ $( "#saveWarningText" ).fadeOut(100); }, 3000); }); } else { //rest of your code }