I have a table of articles that displays in rows on client side. Each articles has a unique id and contains a checkbox to indicate if this article is checked as a favorite. If it is a favorite, then the checkbox is already checked. If not, it is unchecked. Now I need either js or jquery and ajax to update the table in the DB if and when the checkbox condition changes specific to each row. Another challenge is that I am working in cakePHP MVC environment.
function checkbox_click (id, favorite)
{
// see if checkbox is checked
if(favorite==1)
{
$.ajax({
type:'POST',
url:'check_favorite.php', // this external php file isn't connecting to mysql db
data:'id= ' + id + '&favorite=1',
});
}// if
// the checkbox was unchecked
else
{
$.ajax({
type:'POST',
url:'check_favorite.php', // this external php file isn't connecting to mysql db
data:'id= ' + id + '&favorite=0',
});
}//else
}
--html-- this is within a foreach loop.
echo "";
else
echo "";
--php file called by ajax--
//Database Variables - with the variables entered it doesn't connect
$dbhost = 'localhost'; // usually localhost
$dbuser = 'username'; // database username
$dbpass = 'password'; // database password
//Establish connection to MySQL database
$con = @mysql_connect($dbhost, $dbuser, $dbpass);
if (!$con)
die('Unable to connect.' . mysql_error());
mysql_select_db('devcake', $con);
// Get the variables.
$query = "UPDATE mytable SET favorite=".$_POST['favorite'] . "
WHERE id=".$_POST['id'] . ";";
mysql_query($query);
mysql_close($con);
?>
解决方案
This is the code i use (thanks to samuel)
$('input[name=favorite]').live("click",function(){
var id = $(this).attr('id');
if($(this).attr('checked')) {
var favorite = 1;
} else {
var favorite = 0;
}
$.ajax({
type:'GET',
url:'favorites.php',
data:'id= ' + id + '&favorite='+favorite
});
//console.log('id: ' + id + ' Publico: '+publico + 'Value: '+value);
});