Reputation: 89
I have a checkbox. if I check or uncheck the check box then a update query should be run with Ajax call.
If checks the checkbox then 1 should be update and if uncheck then 0 should be update. But it is not working.
Checkbox is:
<input type="checkbox" id="test_done" value="<?php echo $row1['id']; ?>" <?php if(($row1['test_done'])=='1') echo "checked='checked'"; ?> data-toggle="checkbox">
In above $row1['id'] and $row1['test_done'] are columns name, which are coming from another select query.
Ajax Is:
<script type="text/javascript">
$(document).ready(function(){
$("#test_done").click(function(){
var val = $(this).val();
if($(this).is(':checked')){
$.ajax({ type: "POST",
url: "test_done.php",
data: {val:val,apply:'1'}
});
}
else
{
$.ajax({ type: "POST",
url: "test_done.php",
data: {val:val,apply:'0'}
});
}
});
});
</script>
test_done.php is:
include_once("connection.php");
if($_POST['apply']=='1')
{
$val = $_POST['val'];
mysql_query("update patient_package_details set test_done='1' where id='$val'") or die(mysql_error());
}
else
{
$val = $_POST['val'];
mysql_query("update patient_package_details set test_done='0' where id='$val'") or die(mysql_error());
}
Upvotes: 2
Views: 4642
Reputation: 3050
You can use change
event instead of click
event on checkbox. Check if checkbox is checked then send 1 otherwise 0. on php side as we are sending both values, so you will get value using post. You don't need to check value for $_POST["apply"]
. I have set the value of apply
variable, so only one query will work.
$("input:checkbox").on("change", function () {
var val = $(this).val();
var apply = $(this).is(':checked') ? 1 : 0;
$.ajax({type: "POST",
url: "test_done.php",
data: {val: val, apply: apply}
});
});
test_done.php:
include_once("connection.php");
$val = $_POST['val'];
$apply = $_POST['apply'];
mysql_query("update patient_package_details set test_done='$apply' where id='$val'") or die(mysql_error());
Upvotes: 4