Home > OS >  Delete value from database with delete button and checkbox - Syntax error, malformed JSON
Delete value from database with delete button and checkbox - Syntax error, malformed JSON

Time:10-24

I am trying to delete data by using the ID which I've stored in the checkbox input as data-id, or maybe it should be 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...

I will add part of the json...

[{"id":236,"sku":"","name":"","price":"","productType":"","size":"","weight":"","height":"","length":"","width":""},{"id":202,"sku":"sge","name":"gse","price":"10","productType":"dvd","size":"500","weight":"","height":"","length":"","width":""},{"id":162,"sku":"sgbr","name":"sg","price":"10","productType":"","size":"","weight":"","height":"","length":"","width":""},{"id":160,"sku":"dn","name":"afbxf","price":"10","productType":"dvd","size":"500","weight":"","height":"","length":"","width":""},{"id":157,"sku":"sag","name":"af","price":"10","productType":"dvd","size":"500","weight":"","height":"","length":"","width":""}]

The script tags that are in the html file...

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.min.js"></script>

I have once again added Shamiq's and @Nico Haase several suggestions in the the delete.php part, in an attempt to find out what is causing this, however the NULL value is persistent. I don't know if maybe the AJAX request is the culprit, but since I am pretty new to JSON I am having difficulties solving this...

    NULL {message: "Deleted Successfully", status: 200}
message: "Deleted Successfully" status: 200; 
Form data: val[]: 269 this is the ID; 

        without Decoding:  val[]=233 - Syntax error, malformed JSON
        with Decoding:  - Syntax error, malformed JSON

the button tag...

button tag `<button   id="deleteBtn" > MASS DELETE</button>`

The delete function..

   $query = 'DELETE FROM ' . $this->table . ' WHERE id = :id';

   $stmt = $this->conn->prepare($query);

   $this->id = htmlspecialchars(strip_tags($this->id));

   $stmt->bindParam(':id', $this->id);

    if($stmt->execute()) {
        return true;

    } else {
        // printf("Error: %s.\n", $stmt->error);
        ini_set('display_errors',1);
        return false;
    }

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();
            
            
            $product = new Post($db);
                    
            $json = json_decode(file_get_contents("php://input"),true);


$product->id = isset($json['id']) ? count($json['id']) : '';


try {

    $product->delete();
    $response = [
        'message' => "Deleted Successfully",
            'status' => 200
    ];
        echo json_encode($response);
    
    } catch (\Throwable $e) {
        $response = [
            'message' => $e->getMessage()
        ];
        echo json_encode($response);
    }

the table with input...

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

        users.forEach(user => {
            let htmlSegment = `
                <table >
                    <tr> 
                    <th> <input type='checkbox' id='checkbox' name='checkbox[]' data-id=${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) {
    e.preventDefault();


    var val = [];
    
    $(':checkbox:checked').each(function() {
      val.push($(this).attr('data-id'));
    });

    if (val.length === 0) {
      alert("Please select at least one checkbox");
    } else {

    $.ajax({
      type: "DELETE",
      url: "/api/post/delete.php",
      data: {'val':val},
      contentType: "application/json",
      success: function () {
        alert("successfully deleted");
      },
      error: function () {
         console.log("Could not be deleted");
      },
    });
   };
  });
});

CodePudding user response:

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

CodePudding user response:

$.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")
         }
    }

     })
})
  • Related