John Higgins John Higgins - 3 months ago 13
MySQL Question

Ajax updating database when a checkbox is checked

Hi I am trying to update a database table by clicking on a checkbox but it's not working.

HTML:

<input name="no_cage" id="no_cage" type="checkbox" value="1" onclick="chkit(<?php echo $estimate_id; ?>,'no_cage');" <?php echo $checked; ?>


AJAX:

function chkit(estimate_id, no_cage) {
chk=document.getElementById("no_cage").checked;

$.ajax({
type: 'GET',
url: 'ajax.php',
data: { chkYesNo: no_cage, estimate_id: estimate_id}

});
}


ajax.php

<?php

error_reporting(E_ALL);

include($_SERVER["DOCUMENT_ROOT"]."/dbconnect.php");

$get=$_GET['chkYesNo'];

$get_id=$_GET['estimate_id'];
if($get=="1")
{
$sql = "UPDATE estimates SET
no_cage = '1',
cage_linear_feet = '',
cage_doors = '',
cage_options = '',
cage_labor = ''
WHERE estimate_id = '".$get_id."'";

if ($conn->query($sql) === TRUE) {
echo "";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
else
{

}
?>


Can anyone see what is I'm missing? I am no expert and have been playing around with the for quite a while with no luck.

Thanks,

John

Answer

As you are passing 'no_cage' as parameter 2 of your

onclick="chkit(<?php echo $estimate_id; ?>,'no_cage');"

And then passing that to the PHP, via AJAX as

data: { chkYesNo: no_cage, estimate_id: estimate_id}
        ^^^^^^^^

When you get to the PHP code $get will be = no_cage and never as your PHP code expects it to be i.e. 1

$get=$_GET['chkYesNo'];   // which will = `no_cage'`

if($get=="1")

So in short, you are never actually running the query

Also try this when finding if the checkbox is checked as your code will return true or false which may be causing the issue

function chkit(estimate_id, no_cage) {
    chk = document.getElementById("no_cage").checked ? 1 : 0;

    $.ajax({
            type: 'GET',
            url: 'ajax.php',
            data: { chkYesNo: chk, estimate_id: estimate_id}

        });
}
Comments