获取多个复选框值并在jQuery中传递给PHP

时间:2017-03-02 02:16:32

标签: php jquery ajax checkbox

我在下面有多个复选框来添加用户访问权限:

enter image description here

每个模块都有不同的ID。但现在我混淆了如何获取复选框值,然后使用ajax更新它。

示例:

  • 模块位置,我选中创建和编辑。
  • 模块部门我选中仅查看

(具有相同的组ID)

我没有得到逻辑如何将其传递给ajax并根据模块ID和组ID将其保存到数据库。

源代码:

$.ajax(
{
    url: "loadModule.php",
    type: "POST",
    data:
    {
        groupName: $("#groupName").val()
    },
    dataType: "JSON",
    success: function (jsonStr)
    {
        var len = jsonStr.length;
        for(var i=0; i<len; i++)
        {
            var moduleID = jsonStr[i].moduleID;
            var moduleName = jsonStr[i].moduleName;
            var projectName = jsonStr[i].projectName;
            var groupID = jsonStr[i].groupID;
            var chkModule = jsonStr[i].chkModule;
            var chkEdit = jsonStr[i].chkEdit;

            var tr_str = "<tr id='"+jsonStr[i].moduleID+"'>" +
            "<td>" + projectName + "</td>" +
            "<td>" + moduleName + "</td>" +
            "<td align='center'><input type='checkbox' id='"+jsonStr[i].moduleID+"' name='chk[]' class='chk' value='CREATE'/><input type='hidden' id='groupIDInput' value='"+jsonStr[i].groupID+"'/></td>" +
            "<td align='center'><input type='checkbox' id='"+jsonStr[i].moduleID+"' name='chk[]' class='chk' value='EDIT'/></td>" +
            "<td align='center'><input type='checkbox' id='"+jsonStr[i].moduleID+"' name='chk[]' class='chk' value='VIEW'/></td>" +
            "<td align='center'><input type='checkbox' id='"+jsonStr[i].moduleID+"' name='chk[]' class='chk' value='DELETE'/></td>" +
            "</tr>";
            $('.dataShow2').show();
            $("#tData tbody").append(tr_str);
        }
}

我想要的是什么:

  1. 使用ajax
  2. 获取复选框值
  3. 将其传递给PHP以保存到数据库。
  4. JS btnUpdate

    $('#btnUpdate').on('click', function()
        {
            var val = [];
            $(':checkbox:checked').each(function(i){
                val[i] = $(this).val();
            });
    
            var chkCreateInputValue = [];            
            $('input[name^=chkProjectInput]').each(function(){
                chkCreateInputValue.push($(this).val());
            });
    
            $.ajax(
            {
                url: "updateGroupAccess.php",
                type: "POST",
                data:
                {
                    chk: val,
                    groupIDInput: $("#groupIDInput").val(),
                    chkCreateInputValue: chkCreateInputValue
                },
                dataType: "JSON",
                success: function (jsonStr)
                {
                    $("#btnUpdate").attr({disabled: true, value: "Update"}).addClass('btn_inact').removeClass('btn_act');;
                }
            });
        });
    

    和PHP

    if(!empty($_POST['chk']))
                {
                    foreach($_POST['chkCreateInputValue'] as $chkCreateInputValue)
                    {
                        if(!in_array($chkCreateInputValue, $_POST['chk'])){
                            $del = oci_parse($c1, "DELETE FROM WA_GA_TBL_ACCESSMODULES WHERE MODULEID_FK = '$chkCreateInputValue' AND GROUPID_FK = '$groupIDInput'");
                            oci_execute($del);
                        }
                    }
    
                    foreach($_POST['chk'] as $chk)
                    {
                        $qChk = oci_parse($c1, "SELECT * FROM WA_GA_TBL_ACCESSMODULES WHERE GROUPID_FK = '$groupIDInput' AND MODULEID_FK IN ('$chk')");
                        oci_execute($qChk);
                        if(oci_fetch($qChk) > 0)
                        {
                            $sql = oci_parse($c1, "UPDATE WA_GA_TBL_ACCESSMODULES SET CHKCREATE = 'Y' WHERE GROUPID_FK = '$groupIDInput' AND MODULEID_FK IN ('$chk')");
                            oci_execute($sql);
                        }
                        else
                        {
                            $date_added = date("d-M-Y H:i:s");
    
                            $sql = oci_parse($c1, "INSERT INTO WA_GA_TBL_ACCESSMODULES(MODULEID_FK, GROUPID_FK, DATEADDED, ADDEDBY) VALUES('$chk', '$groupIDInput', TO_DATE('$date_added', 'dd-MON-yyyy hh24:mi:ss'), '$getUserID')");
                            oci_execute($sql);
                        }
                    }
                }
                else
                {
    
                    foreach($_POST['chkCreateInputValue'] as $chkCreateInputValue)
                    {
                        if(!in_array($chkCreateInputValue, $_POST['chk'])){
                            $del = oci_parse($c1, "DELETE FROM WA_GA_TBL_ACCESSMODULES WHERE GROUPID_FK = '$groupIDInput'");
                            oci_execute($del);
                        }
                    }
                }
    

2 个答案:

答案 0 :(得分:0)

我的确不是很好,但这样的想法可能会对你有所帮助:

<script>
var data={'CREATE':[],'EDIT':[],'VIEW':[],'EDIT':[]};
var tmp=document.getElementsByName('chk[]');
for(var i=0,j=tmp.length;i<j;i++){
    if(tmp[i].checked){
        data[tmp[i].value].push(tmp[i].id);
    }
}

$.ajax({
    url:'save.php',
    data:{'data':data},
    type:'POST',
    success:function(){
        /*Callback Function*/
    }
});
</script>

<?php
if(isset($_POST['data'])){
    if(count($_POST['data']['CREATE'])){
        /* Do Something */
    }

    if(count($_POST['data']['EDIT'])){
        /* Do Something */
    }

    if(count($_POST['data']['VIEW'])){
        /* Do Something */
    }

    if(count($_POST['data']['EDIT'])){
        /* Do Something */
    }
}
?>

答案 1 :(得分:0)

&#13;
&#13;
const allCheckboxs = document.querySelectorAll('input[type=checkbox');
let data = {
  read: []
  ,write: []
  ,edit: []
  ,delete: []
}

allCheckboxs.forEach(element => {
  element.addEventListener('click', e => {
    const self = e.target
    const className = self.className
    const id = self.dataset.id
    console.log(id)
    if(self.checked){
      data[className].push(id)
    }else{
      const index = data[className].indexOf(id);
      if (index > -1) {
          data[className].splice(index, 1);
      }
    }
    console.log(data)
  })
})

// Do you AWESOME AJAX magic...
&#13;
<p>
  Rainbow Dash: 
  Read <input type='checkbox' class='read' data-id='rainbowdash'/>
  Write <input type='checkbox' class='write' data-id='rainbowdash'/>
  Edit <input type='checkbox' class='edit' data-id='rainbowdash'/>
  Delete <input type='checkbox' class='delete' data-id='rainbowdash'/>
</p>

<p>
  Pinkie Pie: 
  Read <input type='checkbox' class='read' data-id='pinkiepie'/>
  Write <input type='checkbox' class='write' data-id='pinkiepie'/>
  Edit <input type='checkbox' class='edit' data-id='pinkiepie'/>
  Delete <input type='checkbox' class='delete' data-id='pinkiepie'/>
</p>

<p>
  Flutterhsy: 
  Read <input type='checkbox' class='read' data-id='flutterhsy'/>
  Write <input type='checkbox' class='write' data-id='flutterhsy'/>
  Edit <input type='checkbox' class='edit' data-id='flutterhsy'/>
  Delete <input type='checkbox' class='delete' data-id='flutterhsy'/>
</p>
&#13;
&#13;
&#13;