首页 \ 问答 \ PHP / AJAX复选框值(PHP / AJAX checkbox values)

PHP / AJAX复选框值(PHP / AJAX checkbox values)

我正在尝试获取所有选中的复选框值并使用AJAX将它们解析为我的php functin。

我使用foreach尝试获取已选中复选框的每个id。

我的问题是,当我尝试更新数据库时,它不会返回'1',我会在成功时回复。

当我把我的foreach代码拿出来时,它有效。

我的删除按钮是:

<form class="form -dark" id="form-inline" method="POST">
    <div class="btn-group">
        <button type="button" onclick="deleteSelectedTokens()" class="btn -dark" style="margin-left: 5px;" title="Delete all selected tokens"><i class="fa fa-trash"> </i></a>
    </div>
</form>

我的复选框html / php代码是:

<table class="table -dark -striped">
<thead>
    <tr>
        <th style="text-align: center;"><input type="checkbox" id="selectall"/></th>
        <th style="text-align: center;">Token</th>
        <th style="text-align: center;">Date/Time Generated</th>
        <th style="text-align: center;">Status</th>
        <th style="text-align: center;">Durbaility</th>
    </tr>
</thead>
   <tbody>
      <tr>
        <?php

        $username = $_SESSION['username'];
        $token_result = mysqli_query($con, "SELECT id, token, used, time_generated, durability FROM tokens WHERE user_id = '$username' ORDER BY used");
        if(mysqli_num_rows($token_result) > 0) {
            while($token_row = mysqli_fetch_array($token_result)) {

            $result = array($token_row['durability']); $sub_struct_month = ($result[0] / 30) ; $sub_struct_month = floor($sub_struct_month); $sub_struct_days = ($result[0] % 30); $sub_struct = "<i>".$sub_struct_month."</i> month(s) <i>".$sub_struct_days."</i> day(s)";

            echo '                  
            <tr style="text-align: center;">
            <td>
            <center><input type="checkbox" id="checkedTokens" class="checkbox" value='.($token_row['id']).'></center>
            </td>
            <td>
            '.$token_row['token'].'
            </td>
            <td>
            '.($token_row['time_generated']).'
            </td>
            <td>
            '.($token_row['used'] == "0" ? "<span class='label label-primary'><i class='fa fa-check'></i> Valid </span>" : "<span class='label label-primary'><i class='fa fa-fa fa-times'></i> Used </span>").'
            </td>
            <td>
            '.$sub_struct.'
            </td>
            ';
             } }else{ ?>

             <tr>
             <td colspan="12" style="padding: 30px;">
             <div class="alert -dark">
                <div class="alert-icon _text-danger">
                    <i class="fa fa-exclamation-circle"></i>
                </div>
                No tokens in your account
            </div>
            </td>
            </tr>

            <?php } ?>
      </tr>
   </tbody>

注意我需要使用foreach来获取每个复选框的值,这样当我按下删除按钮时我可以删除所选的复选框值。

我的AJAX发送到PHP的功能是:

<script>
function deleteSelectedTokens() {
  var selectedTokens = document.getElementById("checkedTokens").value;

  $.ajax({
      type: "POST",
      url: "includes/form_submit.php",
      data: {
        deleteSelectedTkns: true,
        checked_id: selectedTokens
      },
      success: function(msg){
        if(msg == 1) {
          update_myDays_success();
        } else {
          general_error_forms();
        }
      },
  });
return false;
}
</script>

我认为问题是Javascript ...当我得到复选框的值并发布它们时,我认为它只在checkedTokens id中得到1个值。

我的php接收代码(这不是问题):

$username       = $_SESSION['username'];
$selectedTokens = mysqli_real_escape_string($con, $_POST['checked_id']);
foreach($selectedTokens as $id) {
    $doUpdateDelete = 'DELETE FROM tokens WHERE id = "'.$id.'" AND user_id = "'.$username.'"';
    $result = $con->query($doUpdateDelete) or die("Error");
    if($result)
    {
        echo '1';
    }
    else
    {
        echo 'Failed';
    }
}

我的console.log没有错误。 就像我说的,我认为这是用于获取我的复选框的值没有获得所有值的javascript代码。


I'm trying to get all checked checkbox values and parse them to my php functin using AJAX.

I use foreach to try and get each id of the checked checkbox's.

My problem is that when I try and update the database, it doesn't return '1' which I echo upon success.

When I take my foreach code out, it works.

My delete button is :

<form class="form -dark" id="form-inline" method="POST">
    <div class="btn-group">
        <button type="button" onclick="deleteSelectedTokens()" class="btn -dark" style="margin-left: 5px;" title="Delete all selected tokens"><i class="fa fa-trash"> </i></a>
    </div>
</form>

My checkbox html/php code is :

<table class="table -dark -striped">
<thead>
    <tr>
        <th style="text-align: center;"><input type="checkbox" id="selectall"/></th>
        <th style="text-align: center;">Token</th>
        <th style="text-align: center;">Date/Time Generated</th>
        <th style="text-align: center;">Status</th>
        <th style="text-align: center;">Durbaility</th>
    </tr>
</thead>
   <tbody>
      <tr>
        <?php

        $username = $_SESSION['username'];
        $token_result = mysqli_query($con, "SELECT id, token, used, time_generated, durability FROM tokens WHERE user_id = '$username' ORDER BY used");
        if(mysqli_num_rows($token_result) > 0) {
            while($token_row = mysqli_fetch_array($token_result)) {

            $result = array($token_row['durability']); $sub_struct_month = ($result[0] / 30) ; $sub_struct_month = floor($sub_struct_month); $sub_struct_days = ($result[0] % 30); $sub_struct = "<i>".$sub_struct_month."</i> month(s) <i>".$sub_struct_days."</i> day(s)";

            echo '                  
            <tr style="text-align: center;">
            <td>
            <center><input type="checkbox" id="checkedTokens" class="checkbox" value='.($token_row['id']).'></center>
            </td>
            <td>
            '.$token_row['token'].'
            </td>
            <td>
            '.($token_row['time_generated']).'
            </td>
            <td>
            '.($token_row['used'] == "0" ? "<span class='label label-primary'><i class='fa fa-check'></i> Valid </span>" : "<span class='label label-primary'><i class='fa fa-fa fa-times'></i> Used </span>").'
            </td>
            <td>
            '.$sub_struct.'
            </td>
            ';
             } }else{ ?>

             <tr>
             <td colspan="12" style="padding: 30px;">
             <div class="alert -dark">
                <div class="alert-icon _text-danger">
                    <i class="fa fa-exclamation-circle"></i>
                </div>
                No tokens in your account
            </div>
            </td>
            </tr>

            <?php } ?>
      </tr>
   </tbody>

Notice I need to use foreach to get each check checkbox value so I can remove the selected ones when I press the delete button.

My AJAX send to PHP function is :

<script>
function deleteSelectedTokens() {
  var selectedTokens = document.getElementById("checkedTokens").value;

  $.ajax({
      type: "POST",
      url: "includes/form_submit.php",
      data: {
        deleteSelectedTkns: true,
        checked_id: selectedTokens
      },
      success: function(msg){
        if(msg == 1) {
          update_myDays_success();
        } else {
          general_error_forms();
        }
      },
  });
return false;
}
</script>

I think the problem is the Javascript... when I get the value of the checkboxes and post them, i think it's only getting 1 value inside the checkedTokens id.

My php receive code (this is not the problem) :

$username       = $_SESSION['username'];
$selectedTokens = mysqli_real_escape_string($con, $_POST['checked_id']);
foreach($selectedTokens as $id) {
    $doUpdateDelete = 'DELETE FROM tokens WHERE id = "'.$id.'" AND user_id = "'.$username.'"';
    $result = $con->query($doUpdateDelete) or die("Error");
    if($result)
    {
        echo '1';
    }
    else
    {
        echo 'Failed';
    }
}

My console.log has not errors. Like I said, i think it's the javascript code for getting the value of my checkbox's not getting all the values.


原文:https://stackoverflow.com/questions/45117039
更新时间:2023-06-25 06:06

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)