如果选中/未选中复选框,则插入mySQL查询

时间:2013-01-11 16:08:07

标签: php javascript html ajax

在尝试开发复选框的过程中,基于复选框内的值激活mySQL查询我遇到了一个我无法通过的问题,我现在尝试了以下内容

<input type="checkbox" name="status" onclick="updateStatus(<? echo $data['id']; ?>,this.checked)">

函数“updateStatus”的Javascript / Ajax代码如下

function updateStatus(id,value) {
if (window.XMLHttpRequest) {
    http = new XMLHttpRequest()
} else if (window.ActiveXObject) {
    http = new ActiveXObject("Microsoft.XMLHTTP")
} else {
    alert("Your browser does not support XMLHTTP!")
}
http.abort();
http.open("GET", "../functions/ajax.php?check=update_status&id=" + id + "&checked="+value, true);
http.onreadystatechange = function () {
     if (http.readyState == 4) {
        alert(http.responseText);
     }
 }
 http.send(null)

functions / ajax.php中的PHP函数

if(isset($check) and $check == 'update_status' and isset($_GET['id'])){
    $id = mysql_real_escape_string($_GET['id']);
    $checked= mysql_real_escape_string($_GET['checked']);
if($checked == true) {
    echo "Checked";
} elseif($checked == false) {
    echo "Not checked";
} else {
    echo "Invalid response";
}

使用此代码时,它总是返回“已检查”任何想法?

1 个答案:

答案 0 :(得分:1)

试试这个(代码测试),

<input type="checkbox" name="status" onclick="updateStatus(<? echo $data['id']; ?>,this.checked)">

您将获得第二个参数为true或false;

function updateStatus(id,checked) {
if (window.XMLHttpRequest) {
    http = new XMLHttpRequest()
} else if (window.ActiveXObject) {
    http = new ActiveXObject("Microsoft.XMLHTTP")
} else {
    alert("Your browser does not support XMLHTTP!")
}
http.abort();
http.open("GET", "../functions/ajax.php?check=update_status&id=" + id+"checked="+checked, true);
http.onreadystatechange = function () {
     if (http.readyState == 4) {
        alert(http.responseText);
     }
 }
 http.send(null)

你的PHP将是:

if(isset($check) and $check == 'update_status' and isset($_GET['id']) AND isset($_GET['checked'])){
$id = mysql_real_escape_string($_GET['id']);
$checked= mysql_real_escape_string($_GET['checked']);
if($checked == true) {
$query = mysql_query("SELECT * FROM `check_status` WHERE `user_id` = '$_SESSION[userid]' and `id` = '$id'");
else
 //some other query
//Then i can insert the query based on if the checkbox checked or not.