skip to Main Content

I am trying to delete data by using the ID which I’ve stored in the checkbox input as value=""… The idea is to delete single box/table, or multiple… Is it something with how the ID is stored in the input, or maybe the delete function is completely wrong, I am out of ideas…

Edit: I managed to solve this with changes made in the delete method, which I corrected in this edit…

I have completely redone the delete.php part, in an attempt to find out what is causing this, now I am getting this payload val%5B%5D=339, and I am receiving the following alert {"readyState":4,"responseText":"","status":200,"statusText":"OK"}

The delete function..

 $query = "DELETE FROM `$this->table` WHERE id = ?";
  $stmt = $this->conn->prepare($query);

  $rows_deleted = 0;

  foreach ($ids as $id) {
    $stmt->bindValue(1, $id, PDO::PARAM_INT);

    $stmt->execute();

    $rows_deleted += $stmt->rowCount();
  }

  return json_encode(['rows_deleted' => $rows_deleted]);

the delete.php

                    header('Access-Control-Allow-Origin: *');
                    header('Content-Type: application/x-www-form-urlencoded');
                    header('Access-Control-Allow-Methods: DELETE');
                    
                    
                    include_once '../../config/database.php';
                    include_once '../../models/post.php';
                    
                    //Instantiate db
                    
  $database = new Database();
$db = $database->connect();
$table = 'skandi';
$fields = [];

//Instantiate post
$product = new Post($db,$table,$fields);
$json = json_decode(file_get_contents("php://input"), true);


$product->id = $json['id'];


try {
  $response = $product->delete($product->id);
  echo $response;
} catch (Throwable $e) {
  echo "Error occurred in delete method: " . $e->getMessage();
}
  

the table with input…

async function renderUser() {
        let users = await getUsers(); 
        let html = ``;

        users.forEach(user => {
            let htmlSegment = `
                <table class="box">
                    <tr> 
                    <th> <input type='checkbox' id='checkbox' name='checkbox[]' value=${user.id}> </th>                                           
                    <td>  ${user.sku}</td>
                    <td>  ${user.name}</td>
                    <td>  ${user.price}</td>
                    ${user.size ? `<td> Size: ${user.size} $ </td>` : ""} 
                    ${user.weight ? `<td> Weight: ${user.weight}  Kg</td>` : "" }
                    ${user.height ? `<td>  Height: ${user.height} CM</td>` : ""}
                    ${user.length ? `<td>  Length: ${user.length} CM</td>` : ""}
                    ${user.width ? `<td>  Width: ${user.width} CM</td>` : ""}
                    </tr>
                </table>`;

                html += htmlSegment;
        });

        let container = document.querySelector('.message');
        container.innerHTML = html;
    }
    renderUser();
  };

the AJAX Delete request

$(document).ready(function () {
  $("#deleteBtn").click(function (e) {
    
    let checkboxes = document.querySelectorAll("input[type=checkbox]:checked");

    let ids = [];

    for (let checkbox of checkboxes) {
      ids.push(checkbox.value);
    }
    // Create the query string using the IDs array
    // let queryString = '?' + ids.map((id) => `id=${id}`).join('&');
    let data = {
      id: ids,
    };
    $.ajax({
      url: "/api/post/delete.php",
      type: "DELETE",
      data: JSON.stringify(data),
      dataType: "json",
      contentType: "application/json",
      success: function (response) {
        console.log(response);
      },
      error: function (error) {
        console.log(error);
      },
    });
  });
});

2

Answers


  1. $.ajax({
        type:'POST',
        url:'delete.php',
        data:{del_id:del_id},
        success: function(data){
             if(data=="YES"){
                 $ele.fadeOut().remove();
             }else{
                 alert("can't delete the row")
             }
        }
    
         })
    })
    
    Login or Signup to reply.
  2. Change the header('Content-Type: application/json'); to header('Content-Type: application/x-www-form-urlencoded');

    For the delete requests, it requires the application/x-www-form-urlencoded header to be declared, since HTML doesnโ€™t support the DELETE method, we are using it artificially.

    Hope this will help you and others in the future ๐Ÿ™‚

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search