jquery ajax post data in php only works for the first time-ThrowExceptions

Exception or error:

I’m trying to delete data using jquery ajax in PHP. I’m able to delete the data for the first time but it doesn’t work the second time. It only works when i refresh the page after the first time. I checked the HTML response by ajax to make sure nothing wrong but it still not works. Here is my code.

index.php

 <div class="container">
        <br>
        <button class="btn btn-primary" data-toggle="modal" data-target="#insert">Thêm sinh viên</button>
        <h1 align="center">Bảng sinh viên</h1>
        <table class="table">
            <thead>
                <tr>
                <th scope="col">Mã SV</th>
                <th scope="col">Tên</th>
                <th scope="col">SĐT</th>
                <th scope="col">Giới tính</th>
                <th scope="col">Hành động</th>
                </tr>
            </thead>
            <tbody id="list">
                <?php include('show.php') ?>
            </tbody>
        </table>
    </div>

AJAX

  $(".delete").on('click',function(){
            var id = $(this).data('id');
            var result = confirm("Bạn có muốn xoá sinh viên này không ?");
            if(result){
                $.ajax({
                    type: "POST",
                    url:"delete.php",
                    data: {'id':id},
                    success: function(response){
                        alert("Xoá thành công");
                        document.getElementById("list").innerHTML= response;
                    }
                })
            }
        })

delete.php

require_once('db.php');
    $real_id = $_POST['id'];
    $sql = "DELETE FROM students WHERE real_id = ?";
    //DELETE FROM table_name WHERE condition;
    $stmt  = $mysqli->prepare($sql);
    $stmt->bind_param("s",$real_id);
    $stmt->execute();
    include("show.php");

show.php

$data ="";
    while($row = $result->fetch_assoc()){

        $data .="<tr>";
        $data .= "<td>".$row['id']."</td>";
        $data .= "<td>".$row['name']."</td>";
        $data .= "<td>".$row['phone']."</td>";
        switch ($row['sex']) {
            case "1":
                $sex = "Nam";
                break;
            case "2":
                $sex = "Nữ";
                break;
            case "3":
                $sex = "Khác";
                break;
        }
        $data .= "<td>".$sex."</td>"; 
        $realid = $row['real_id'];
        $data .= "<td><button class='btn btn-danger delete' data-id='$realid'>Xoá</button></td>";
        $data .="</tr>";  
    }
    echo($data);
How to solve:

Edit your Jquery in to this:

$(document).on('click', 'button.delete',function(){ //<-----
     var id = $(this).data('id');
     var result = confirm("Bạn có muốn xoá sinh viên này không ?");
     if(result){
          $.ajax({
               type: "POST",
               url:"delete.php",
               data: {'id':id},
               success: function(response){
                    alert("Xoá thành công");
                    document.getElementById("list").innerHTML= response;
               }
          })
     }
     return false;
});

Or
You can do the same but different way:

show.php

...

$data .= "<td><button class='btn btn-danger delete' onclick='deleteRecord('$realid')'>Xoá</button></td>";

...

And create a Jquery function:

function deleteRecord(id){
    var result = confirm("Bạn có muốn xoá sinh viên này không ?");
     if(result){
          $.ajax({
               type: "POST",
               url:"delete.php",
               data: {'id':id},
               success: function(response){
                    alert("Xoá thành công");
                    document.getElementById("list").innerHTML= response;
               }
          })
     }
}

Hope it will helps.

Answer:

Since you are appending button element to data dynamically.

$(".delete").on('click',function() {
 // ..... this will not work second time.
}

Try the following

$(document).on('click', '.delete' function(){
 // This should work.
});

Leave a Reply

Your email address will not be published. Required fields are marked *