0

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);
      },
    });
  });
});
Bork
  • 13
  • 1
  • 4
  • 1
    a) the option name is `contentType`, not `ContentType`, and b) you are not actually sending JSON - you passed an object, but jQuery will not encode that as JSON on its own. – CBroe Oct 17 '22 at 08:16
  • @CBroe any advice? I am kind of stuck. Thanks for the comment so far. – Bork Oct 17 '22 at 08:42
  • Check the "the AJAX Delete request" JQuery code, and the console log the 'val' If it has the relevant data if it has data then move to the next step of debugging, next, check the 'the delete.php' where `$product->id = $data->id;` print it and exit using `print_r($data); exit();` or use `var_dump($data); exit();` In case the id is null or format is wrong you can view the data. Seems like there is something wrong with the `$data` variable, you are receiving in the post – Shamiq Oct 17 '22 at 13:58
  • @Shamiq Hey, when console.log(val) it logs the ID that I've selected, however the var_dump($data) gives a NULL value, I don't understand why... – Bork Oct 17 '22 at 14:01
  • Try one more thing, `var_dump($_DELETE);exit();` just below `$product` variable – Shamiq Oct 18 '22 at 15:55
  • Hey @Shamiq, I am getting ```Warning: Undefined variable $_DELETE in api\post\delete.php on line 21 NULL``` – Bork Oct 19 '22 at 08:58
  • hi @Bork, change the `Content-Type` header to `header('Content-Type: application/x-www-form-urlencoded');` – Shamiq Oct 21 '22 at 06:54
  • Also check if `echo "REQUEST_METHOD is: {$_SERVER['REQUEST_METHOD']}" exit();` is printing `REQUEST_METHOD is: DELETE` – Shamiq Oct 21 '22 at 06:56
  • You are free to remove: `$_DELETE` it won’t work. – Shamiq Oct 21 '22 at 06:57
  • Hey @Shamiq it does say ```REQUEST_METHOD is: DELETE```, changed the content-type, now the AJAX delete request says successfully deleted, however in the network console it still prints out ```Decoding: - Syntax error, malformed JSON Warning Attempt to read property "id" on array in api\post\delete.php on line 29 {"message":"Product Deleted"}``` meaning ```$product->id = $data->id; ``` – Bork Oct 21 '22 at 08:11
  • Seems like the issue has been resolved now use `$product_json = json_decode($product);` then use `$product_json->id'` if it gives the error then instead of adding and use `echo '
    '; print_r($product); echo '
    ';` in such a way you can check the data in the `$product` and use it accordingly, the error mentioned above says the data you are trying to access is an array not object. Yes `DELETE` request sends different headers and those headers should be declared in the file to match the expectations. Let me know if it worked :)
    – Shamiq Oct 24 '22 at 08:29
  • Does this answer your question? ["Notice: Undefined variable", "Notice: Undefined index", "Warning: Undefined array key", and "Notice: Undefined offset" using PHP](https://stackoverflow.com/questions/4261133/notice-undefined-variable-notice-undefined-index-warning-undefined-arr) – Nico Haase Oct 24 '22 at 08:37

2 Answers2

-1

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 :)

Shamiq
  • 89
  • 1
  • 5
  • Please add some explanation to your answer such that others can learn from it. If the DELETE request is not working properly, how should changing the response header resolve that? – Nico Haase Oct 24 '22 at 08:39
-2
$.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")
         }
    }

     })
})
  • 3
    Please explain how this solves the question/issues? – DarkBee Oct 17 '22 at 13:24
  • kindly use the ajax call within the script tag with libraries type is defined the request type POST or GET The data is using the send request The URL points out the URL. success is used for after get the result function – Aravindhan Radhakrishnan Oct 17 '22 at 13:26
  • @AravindhanRadhakrishnan I forgot to add the script tags, I've included them now in the question... Thanks for the suggestion, I have implemented it, however I still get the same message, I really don't understand why the ID is null... – Bork Oct 17 '22 at 13:37