user5996816
user5996816

Reputation:

Simple ajax function send NULL id

I'm trying to make simple delete ajax function. I'm not very good ad JS at all but when I click on button delete I can see in Chrome Dev Console that id = NULL and when I refresh the page the entry is back. The ajax function is pretty simple

$("body").on("click",".remove-item",function(){
    var entry_id = $(this).parent("td").data('entry_id');
    var c_obj = $(this).parents("tr");

    $.ajax({
        dataType: 'json',
        type:'POST',
        url: 'delete.php',
        data:{entry_id:entry_id}
    }).done(function(data){
        c_obj.remove();
        toastr.success('Item Deleted Successfully.', 'Success Alert', {timeOut: 5000});

    });
});

And the button

<button  class="btn btn-danger remove-item" > Delete</button>

And this is the delete.php

$entry_id  = $_POST["entry_id"];
$stmt = $pdo->prepare("DELETE FROM entries WHERE entry_id = :entry_id"); 
$stmt->bindParam(':entry_id', $entry_id, PDO::PARAM_INT);
$stmt->execute();

echo json_encode([$entry_id]);

Any idea what can be wrong?

update. The table

    echo '<table class="table">
        <thead>
            <tr>
                <th>#</th>
                <th>Name</th>
                <th>Transaction Quote</th>
                <th>Action</th>
            </tr>
        </thead>';
        foreach($pdo->query("SELECT * FROM entries ORDER BY entry_id DESC LIMIT 20") as $row){                                                          
            echo '
                <tbody>
                <tr>
                    <td>'.$row['entry_id'].'</td>
                    <td>'.$row['entry_name'].'</td>
                    <td>'.$row['entry_transaction_quote'].'</td>
                    <td><button  class="btn btn-sm btn-danger remove-item" ><i class="glyphicon glyphicon-trash"></i> Delete</button></td>
                </tr>
                </tbody>  ';
        }
        echo '  </table>

Upvotes: 1

Views: 104

Answers (2)

Nikhil Vaghela
Nikhil Vaghela

Reputation: 2096

Try this

Html should be like

<tr entry_id="<?=$row['entry_id']?>">
   <td><button  class="btn btn-sm btn-danger remove-item" ><i class="glyphicon glyphicon-trash"></i> Delete</button></td>
</tr>

Js code should be like

var entry_id = $(this).parent().parent().attr("entry_id");

Upvotes: 0

JYoThI
JYoThI

Reputation: 12085

Change your td with class name

 <td class="entry_id">'.$row['entry_id'].'</td>

jquery

var entry_id = $(this).parent("td").parent("tr").find('.entry_id').text().trim();

Upvotes: 2

Related Questions