I have a checkbox and I need that when it is "checked" to alter a MySQL Table value to "yes" and if it's checked when you uncheck to "no".
I want to accomplish this with Ajax. How can this be done?
Use jQuery and PHP.
This is an example in jQuery:
$.post("test.php", { isChecked:$('#checkbox_id').attr('checked') } );
This statement should be defined at either in the <head></head>
, or in a separate JavaScript file.
And in your PHP code you can check for the isChecked
POST
variable:
if($_POST('isChecked')==1)
{
//Set MySQL table to 1.
}
else
{
//Set MySQL table to 0.
}
Here is a reference on how to use post. And here's how you can use PHP to update MySQL table.
You use the checkbox's onchange event handler to issue an XmlHttpRequest to some server-side code to update your table.
I'm not sure what's wrong. This is my PHP for the test.php in the example from Ngu Soon Hui:
<?php
$con = mysql_connect("localhost","root","root");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("FACT", $con);
if($_POST('isChecked')==1) // THIS IS LINE 21
{
mysql_query("UPDATE Orc SET CON = 'CHECKED'
WHERE UID = '1'");
}
else
{
mysql_query("UPDATE Orc SET CON = 'NO'
WHERE UID = '1'");
}
mysql_close($con);
?>
Nothing is hapening and if try to open the page (test.php) I'm faced with the following error:
Fatal error: Function name must be a string in /MAMP/htdocs/Fact/change.php on line 21
I can't seem to spot what's wrong.
Note: I'm just trying to update a single record just to test if it's working. My checkboxes names are dynamically generated but I think I know how to handle that part.
Another update:
I'm still having trouble with this,
My PHP code for the test.php:
$con = mysql_connect("localhost","root","root");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("FACT", $con);
if($_POST['isChecked']==TRUE) // SEE THIS LINE PLEASE
{
mysql_query("UPDATE Orc SET CON = 'CHECKED'
WHERE UID = '1'");
}
else
{
mysql_query("UPDATE Orc SET CON = 'NO'
WHERE UID = '1'");
}
mysql_close($con);
I have commented one of the above lines, originally it was "== 1" but this worked only fine for deselecting, I could not change the value back to "CHECKED". Now I tried changing for "TRUE" and now I'm unable to set it to "NO"...
What is going wrong? And how does one go about debugging these kind of errors? Is there any way to have feedback from the JavaScript being executed?