Benza
Benza

Reputation: 175

PHP / AJAX checkbox values

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.

Upvotes: 0

Views: 139

Answers (2)

Bolot Kalil
Bolot Kalil

Reputation: 26

You can send json of checked items:

<script>
    var selectedTokens = []; 
    $('#checkedTokens:checked').each(function(key, value){
        selectedTokens.push($(value).val());
    });
    $.ajax({
        type: "POST",
        url: "includes/form_submit.php",
        data: {
           deleteSelectedTkns: true,
           checked_id: JSON.stringify(selectedTokens)
    },
    success: function(msg){
      if(msg == 1) {
        update_myDays_success();
      } else {
        general_error_forms();
      }
    },
  });
  </script>

And your php code mysqli_real_escape_string give only string we should convert json to get array:

$selectedTokens = json_decode($_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';
    } 
}

Upvotes: 1

Emile Eichenberger
Emile Eichenberger

Reputation: 121

In html it is not allowed to assign the same id to multiple tags. (As already mentioned in the comments.)

If you place your checkboxes on a <form id="some_id">, and give every checkbox a unique name and id, you can use the function $('#some_id').serialize() to get the data of the form and post it to the server.

Upvotes: 0

Related Questions