简体   繁体   中英

Creating mysql delete link for every row in table, delete it with ajax and update table list

So I have table inside database. I have input field and based on input I call ajax to list table.

a = $("#a").val();
    $.ajax({
        type: "POST",
        url: "list.php",
        data: {a: a},
        success: function(response){
          $('#b').html(response);

        }
    });
     return false;

and my list.php :

$result = $dbc->query("SELECT * FROM table WHERE a = '$a'");

while ($row = $result->fetch_array()) {
$x = $row['ID'];
$y = $row['a'];
$z = $row['b'];
echo $x;
echo " ";
echo $y;
echo " ";
echo  '<input value="';
echo $z;
echo '" type="number" />';
echo '<a href="delete.php?ID=';
echo $x;
echo '"><span class="delete">x</span>';
echo '<br/>';
}

and delete.php :

$ID = $_REQUEST['ID'];
$sql = "DELETE FROM table WHERE ID=" . $ID;    
if($dbc->query($sql) === TRUE) {
echo 'deleted';
} else {
echo "Error deleting record; ". $conn->error;
}
$conn->close();

So when I click on x near list of table rows it really delets row but via php. I need to do it via ajax. I tried this but doesn't work.

$('.delete').click( function (e) {
$.ajax({
        type: "POST",
        url: "delete.php",
        data: {x: x, y: y, z: z},
        success: function(response === 'deleted'){
          $.ajax({
        type: "POST",
        url: "list.php",
        data: {a: a},
        success: function(response){
          $('#a').html(response);

        }
     });
     return false;
     });

        }
    });
     return false;
});

So logic is - when I click on x it prevent default and calls delete.php and delete row based on posted id and on success calls ajax again to update list without deleted row.

Hint?

As pointed out in the comments, you have a syntax error with your success function:

success: function(response === 'deleted')

When you click the "x", if your row is not being deleted in the database, then either the row with the information specified does not exist, or you are not properly sending and retrieving the POST data.

I noticed that when you send the POST request to delete.php, the keys you are sending are "x", "y", and "z": data: {x: x, y: y, z: z} . However, in delete.php you are looking for the request variable identified by "ID": $ID = $_REQUEST['ID']; . I believe that this is where your problem exists. You should make sure that your keys match.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM