如何使用jquery检查复选框时更新数据库?

时间:2016-03-21 19:36:28

标签: php jquery mysql ajax post

我正在尝试使用jquerys $ .post或$ .ajax检查复选框(1或0)时更新数据库中的值。我真的很感激一些帮助。这是我的代码:

HTML

<div class="onoffswitch">
     <?php
    $yesno = (bool)$baner['noti'];
    $checked = ($yesno) ? 'checked="checked"' : '';  
     ?>
   <input type="checkbox" name="onoffswitch" class="onoffswitch-checkbox" value="1" id="myonoffswitch" <?php echo $checked; ?>>
   <label class="onoffswitch-label" for="myonoffswitch"></label>
</div>

的jQuery

$(function(){
    $("#myonoffswitch").click(function(){
        $.post("notification.php");
        })
    });

notification.php

connections stuffs...

$yesno = ( isset($_POST['onoffswitch']) ) ? 1 : 0;
$sql = "UPDATE baner SET noti='$yesno'";

2 个答案:

答案 0 :(得分:3)

你几乎拥有它。您只需要阅读您的复选框状态并将其与POST请求一起发回。

$(function(){
    $("#myonoffswitch").click(function(){
        var isOn = $("#myonoffswitch").prop("checked");
        $.post("notification.php", { 'onoffswitch': isOn }, function (result) {
            //handle success here
        });
    });

答案 1 :(得分:0)

使用 $.ajax 尝试此操作。 广泛用于没有重定向页面的更新数据。

$("#myonoffswitch").click(function(){
    $.ajax({
       var onoffswitch=$('#myonoffswitch').val();
       type: "POST",
       url: "notification.php", //Relative or absolute path to notification.php file
       data: {onoffswitch: onoffswitch},
       success: function(response) {
                content.html(response);
       }
    });  

});

<强> notification.php

connections stuff...

$yesno = ( isset($_POST['onoffswitch']) ) ? 1 : 0;
$sql = "UPDATE baner SET noti='$yesno'";