Hello everyone
So, my objective is to update four rows in my database (id-> int , status->tinyint) from 0 to 1 and vice verca using a checkbox. This should be done without refreshing the page and using a form without submit button. Based on my research, I was able to write the following code but not sure if it is correct as I am very new to this part. Can someone please help me with this, I have been trying to do this for a very long time.
Thanks you
Index.php
<form id="myform" method="post" action="">
<input type="checkbox" class="ids" name="ids[]" value="1">
<input type="checkbox" class="ids" name="ids[]" value="2">
<input type="checkbox" class="ids" name="ids[]" value="3">
<input type="checkbox" class="ids" name="ids[]" value="4">
</form>
<div id="response"></div>
<script>
$(document).ready(function() {
$('#myform').click(function() {
var state = ($(this).is(':checked')) ? '1' : '0';
$.ajax({
url: "test.php",
type: "post",
data: $('.ids:checked').serialize(),state: state
success: function(data) {
$('#response').html(data);
}
});
});
});
</script>
test.php
<?php
include_once("db.php");
if (isset($_POST['ids'])) {
$id_value = $_POST['ids'];
$state = (int)$_POST['state'];
foreach($id_value as $check) {
$sql_check = "UPDATE toggle SET status= '$state' WHERE id = '$check' ";
$result_check = mysqli_query($conn,$sql_check);
if($result_check){
echo "sucess";
}else{
echo "failure";
}
}
}
?>