0

I'm using Jquery and Ajax method to delete my data using the checkbox. I'm not sure why my data will not delete without a hard refresh. The success function in Ajax doesn't seem working. I do not know what's the problem here. Can someone kindly help me with this problem?

 <script type="text/javascript">
    $(document).ready(function(){
      $('#btn_delete').click(function(){
        // if(confirm("Are you sure you want to delete these products?"))
        // {
            var id=[];

            $(':checkbox:checked').each(function(i){
              id[i] = $(this).val();

            });

            if(id.length === 0){
              alert("Please select at least one product");
            }else if (confirm("Are you sure you want to delete these products?")){
                $.ajax({
                  url:'includes/delete-in-bulk.php',
                  method:'POST',
                  data:{id:id},
                  success:function(){
                    for(var i=0; i<id.length; i++){
                      $('tr#'+id[i]+'').css('background-color','#ccc');
                      $('tr#'+id[i]+'').fadeOut('slow');
                    }
                  }

                });
            
        }
        else{
          return false;
        }

      });

    });
  </script>

Here are my PHP codes

<tbody id="products">
                  <?php
                  if (!$tot_products) {
                    echo '
                      <div class="col-12">
                        <div class="badge badge-danger">No Products Found</div>
                      </div>
                    ';
                  } else {
                    $i = 1;
                    while ($row = $query->fetch_assoc()) {
                  ?>

                  <tr>
                    <td>
                        <input type="checkbox" id="checkItem" name="product_id[]" class="delete_products"value="<?php echo $row["product_id"]; ?>">
                        </td>
                    <td>
                      <img src="images/product-main/<?php echo !empty($row['product_photo']) ? $row['product_photo'] : ''; ?>" style="height: 50px; width: 50px;">
                    </td>
                    <td>
                      <?php echo $row['product_title']; ?>
                    </td>
                    <td>
                      <?php echo $row['product_sku']; ?>
                    </td>
                    <td>
                      <?php echo !empty($row['seller_fullname']) ? $row['seller_fullname'] : 'N/A'; ?>
                    </td>
                    <td>
                      <?php echo !empty($row['product_price']) ? $row['product_price'] : 'N/A'; ?>/<?php echo !empty($row['product_unit']) ? $row['product_unit'] : ''; ?>
                    </td>
                    <td>
                      <?php echo !empty($row['product_created']) ? $row['product_created'] : 'N/A'; ?>
                    </td>
                    <td>
                      <?php echo !empty($row['product_stock']) ? $row['product_stock'] : 'N/A'; ?> <?php echo !empty($row['product_unit']) ? $row['product_unit'] : ''; ?>
                    </td>
                    <td>
                      <a href="#productstatus_modal<?php echo $i; ?>" data-sfid="<?php echo $i; ?>" data-toggle="modal" title="Click to change the status"><?php echo ($row['product_status'] != 0) ? '<b class="text-success">In Stock</b>' : '<b class="text-danger">Out of Stock</b>'; ?></a>
                    </td>
                    <td>
                      <a class="text-primary" href="view-product.php?pid=<?php echo $row['product_id']; ?>" style="text-decoration: none;" title="View Product">
                        <i class="fa fa-eye"></i>
                      </a>&emsp;
                      <a class="text-danger" href="includes/delete-product.php?pid=<?php echo $row['product_id']; ?>" style="text-decoration: none;" title="Delete Product" onclick="return confirm('Are you sure want to delete this product?');">
                        <i class="fa fa-trash-o"></i>
                      </a>
                    </td>
                  </tr>
                    <!-- The Modal -->
                    <div class="modal hide fade in" role="dialog" aria-hidden="true" id="productstatus_modal<?php echo $i; ?>">
                      <div class="modal-dialog modal-dialog-centered">
                        <div class="modal-content">
                          <!-- Modal body -->
                          <div class="modal-body">
                            <div class="float-right mb-3">
                              <button type="button" class="close" data-dismiss="modal" style="color:#ed1c25;">&times;</button>
                            </div>
                            <div class="mt-5 col-12">
                                <p class="font-weight-bold mb-3">Product Name: <?php echo $row['product_title']; ?></p>
                                <form action="includes/product-details.php" method="POST">
                                  <div class="form-group">
                                    <label><b>Change Product Status</b></label>
                                    <select name="product_status" class="form-control product_status" required>
                                        <option disabled selected>Select Option</option>
                                        <option value="1" <?php if($row['product_status'] == 1) { echo ' selected="selected"'; } ?> >In Stock</option>
                                        <option value="0" <?php if($row['product_status'] == 0) { echo ' selected="selected"'; } ?> >Out of Stock</option>
                                    </select>
                                  </div>
                                  <div class="form-group">
                                      <label><b>Product Stock <?php echo !empty($row['product_unit']) ? 'in ' .$row['product_unit'] : ''; ?></b></label>
                                      <input type="number" step="any" placeholder="Enter your Stock" name="product_stock" class="form-control textInput" />
                                  </div>
                                  <div class="float-right">
                                    <input type="hidden" value="<?php echo $row['product_id']; ?>" name="product_id">
                                    <button type="submit" name="chg_prod_status" class="btn btn-primary">Save</button>
                                  </div>
                                </form>
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                  <?php
                         $i++;
                      }
                    } 
                  ?>
                </tbody>
              </table>
              
            </div>
          </div>
 <div class="d-flex p-4 justify-content-around">
                    <div class="row">
<button type="button" name="btn_delete" id="btn_delete" onClick="window.location.href=window.location.href" value="True" class="btn btn-danger btn-icon-split m-2">
                            <span class="icon text-white-50">
                                <i class="fa fa-trash-o"></i>
                            </span>
                            <span class="text">Delete Product</span>
                        </button>
                    </div>
                </div>

here is my delete-in-bulk.php codes

<?php
include '../session.php';

if(isset($_POST["id"]))
{
 foreach($_POST["id"] as $pid)
 {
  $sql = "DELETE FROM products WHERE id = '".$pid."'";
  mysqli_query($conn, $sql);
 }
}
?>

the codes above are the PHP codes that I added for my checkbox function. The data can be deleted successfully in the database but it won't be able to delete the data that display on the page without the hard refreshh please help me resolve this problem. I could not find any problem in the browser console. Thanks in advance

yw13
  • 248
  • 1
  • 13
  • Provide your php code – Mohamed-Yousef Feb 18 '21 at 03:02
  • @Mohamed-Yousef i've added my php code above – yw13 Feb 18 '21 at 03:09
  • Long way .. I don't know what is `tot_products` come from .. Also `data:{id:id},` means you pass the ids to php and catch it using `$_POST['id']` which is not found in your php code .. anyway try to directly access `http//mywebsite.com/includes/delete-in-bulk.php` and test the php first then go to another step which is connecting the ajax with php – Mohamed-Yousef Feb 18 '21 at 03:17
  • Also *I could not find any problem in the browser console* because you need to `console.log` the returned data with success/error callback functions see [HERE](https://stackoverflow.com/a/14217926/3385827) – Mohamed-Yousef Feb 18 '21 at 03:22
  • @Mohamed-Yousef i added the delete-in-bulk codes. Can you assist me in resolving this problem? – yw13 Feb 18 '21 at 03:26
  • I posted an answer please check it – Mohamed-Yousef Feb 18 '21 at 03:40

1 Answers1

0

Ok simple ajax/php test

1st: The ajax part

$.ajax({
     url:'includes/delete-in-bulk.php',
     method:'POST',
     data:{id:id},
     success:function(response){
         console.log(response);
     },
     error: function(jqXHR, textStatus, errorThrown) {
       console.log(textStatus, errorThrown);
     }
});

You may need to check includes/delete-in-bulk.php this path it will be much easier for you to use the full url path http://mywebsite.com/includes/delete-in-bulk.php

2nd: in php

<?php
 print_r($_POST['id']);
?>

Now you should see the ids printed out in the console

3rd: In php

<?php
 $ids = $_POST['id'];
 foreach($ids as $pid){
   echo $pid;
 }
?>

Now you should see the ids printed out in the console

4th: check the session.php path .. start locate it from delete-in-bulk.php file maybe its ../../session.php

5th: Add your database code and use

if(mysqli_query($conn, $sql)){
 echo 'ok';
}

Now you should see the ok in the console

After all of this now everything is ok to do anything in the ajax success callback

Mohamed-Yousef
  • 23,946
  • 3
  • 19
  • 28