2011-06-08 26 views
0

因此,我有一个待办事项由用户输入动态填充的项目列表。每个选项旁边都有一个复选框,当选中时,MySQL数据库中待办事项的状态应该被修改。PHP和JavaScript在MySQL中的更改状态

我觉得做这样的:

echo "<input type='checkbox' onclick='changeState($theid);' />"; 

其中$ theid是在表中的行ID。

javascript/jquery changeState()函数看起来能够正确更新数据库么?

这里是JavaScript代码,似乎根本不工作(它被放置在HTML文件的<head>

<script language="javascript"> 

function changeState() 
{ 
    jQuery('body').delegate('input[type="checkbox"][data-state-id]', 'change', function(event){ 
    jQuery.post('updatedata.php', { 
     'rowid': jQuery(this).attr('data-state-id') 
     //'state': jQuery(this).is(':checked') 
    }); 
}); 

} 

</script> 

任何想法,为什么

+0

任何有关MySQL表的详细信息包含状态被改变? – Tadeck 2011-06-08 22:48:04

回答

2

你应该阅读更多关于AJAX调用,最好用.post()功能,然后在数据库中更新服务器端的数据。

祝你好运。

基于从the documentation of jQuery's .post()的例子,可以实现这样的事情(在JavaScript中使用jQuery):(例如,在updateState.php)

var changeStatus = function(id){ 
    $.post("updateState.php", { 'id': id }); 
}; 

,并在服务器端:

$id = (int)$_POST['id']; 
// here make some query using $id to update the state 
// in a manner you prefer 

编辑:

但是我宁愿这样的事情:

在服务器1侧),显示该复选框(通知不同报价和(int)铸造):在JavaScript中某处

echo '<input type="checkbox" data-state-id="' . (int)$theid . '" />'; 

2)(参见jsfiddle作为证明):

jQuery(main_container).delegate('input[type="checkbox"][data-state-id]', 'change', function(event){ 
    jQuery.post('update_state.php', { 
     'id': jQuery(this).attr('data-state-id'), 
     'state': jQuery(this).is(':checked') 
    }); 
}); 

3) (在update_state.php):

$id = (int)$_POST['id']; 
$state = (bool)$_POST['state']; 
$query = 'UPDATE `states` SET `state`="' . $state . '" WHERE `id`="' . $id . '";'; 
// here execute the query, obviously adjusted to your needs 
+0

除了我猜它会是$ _POST ['id'] ...好吧这看起来很有趣,现在就试试吧.. – Sev 2011-06-08 22:56:35

+0

@Sev是的,你是对的 - 我犯了一个错误。如果你会按照编辑后的版本,请记住可能有一些错误(也许'$ state'被还原,我不确定),但是有一些改进,比如:1)删除内联JS,2)委托事件,3)使用HTML5的_custom data_,4)通过当前状态与ID,5)使用'onchange'而不是'onclick',6)铸造作为保护免受SQL注入等。 – Tadeck 2011-06-08 23:03:09

+0

@Sev关于'$ state'恢复 - 我已经检查过,它没有被恢复(请参阅[jsfiddle](http://jsfiddle.net/bYZBy/)),因此您可能希望将ID与更新后的状态一起传递。 – Tadeck 2011-06-08 23:09:06

1

你不需要想的?如:“JavaScript将更新SQL记录”,将其视为“JavaScript会告诉API更新该ID”。

所以基本上你必须做的是用PHP创建一个API;然后使JavaScript通过$.ajax执行正确的API调用,th在应该做的伎俩。

$.ajax({ 
    url: '/path/to/api.php', 
    type: 'POST', 
    dataType: 'xml/html/script/json/jsonp', 
    data: {param1: 'value1'}, 
    complete: function(xhr, textStatus) { 
    //called when complete 
    }, 
    success: function(data, textStatus, xhr) { 
    //called when successful 
    }, 
    error: function(xhr, textStatus, errorThrown) { 
    //called when there is an error 
    } 
});