ajax更新数据库mysql,如何使用Ajax来更新MySQL数据库复选框时,情况发生改变?

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);

});

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值