简体   繁体   中英

How update records in the database and remove a table row on button click using ajax?

So I have created an HTML table with dynamic rows. On the end the every row there is a button. When that button on the particular row is clicked, the row needs to removed without page refresh.

So I'm trying to do it by changing the values of column in database on button click. There is a field named 'status' in my database, which is initially set to 'unchecked'. But when I click the button, the update query is to be triggered hence changing the 'status' field to 'checked' on that particular row, and removing that particular.

newCust.php

<table class="table table-bordered table-striped table-light table- 
responsive text-nowrap">
<thead class="thead-dark">
<tr>
<th class="col"><label> nID</label></th>
<th class="col"><label> CUSTOMER NAME </label></th>
<th class="col"><label> ADDRESS </label></th>
<th class="col"><label> CITY </label></th>
<th class="col"><label> STATUS </label></th>
</tr>
</thead>
<tbody>

<?php
<!-- GETTING DATA FROM THE TABLE WHERE STATUS FIELD IS UNCHECKED -->
$query = "select * from mx_newcustomer where status = 'unchecked'";
$result = mysqli_query($db,$query);
while($res = mysqli_fetch_array($result)){
$nID = $res['nID'];
?>
<tr>
<td><?php echo $nID;  ?></td>
<td><?php echo $res['customername'];  ?></td>
<td><?php echo $res['address'];  ?></td>
<td><?php echo $res['city'];  ?></td>
<td><button type="button" id="button<?php echo $nID;  ?>" class="btn btn- 
dark" >Ok</button></td>
</tr>

<script>
<!-- AJAX TO UPDATE RECORDS IN THE DATABASE-->
$(document).ready(function () {
$("#button<?php echo $nID ?>").click(function(){
alert('Test');
jQuery.ajax({
type: "POST",
url: "updateCust.php",

<--TRYING TO 
PASS THE CLICKED BUTTON ID. I BELIEVE THIS IS WHAT I'M DOING WRONG-->
data:  {"nID":$('#button<?php echo $nID ?>').serialize()}, 
success: function(response)
{
 alert("Record successfully updated");
}
});
});
});

</script>

updateCust.php

$db = mysqli_connect("credentials");
$nID = $_POST['nID'];
$query = "UPDATE mx_newcustomer SET status = 'checked' WHERE nID = 
'$nID'";
$res = mysqli_query($db, $query);

error_reporting(E_ALL);
ini_set('display_errors','On');

I'm not getting any errors, but the update query is not being triggered either. The expected result is remove the table row whose button has been clicked, without the page being refreshed.

Don't use .serialize() , it returns a string in the form name=value . But your button doesn't have a name or value, so there's nothing to serialize.

Change it to:

data:  {"nID": <?php echo $nID ?>}, 

To delete the row, you can use:

success: function() {
    $("#button<?php echo $nID?>").closest("tr").remove();
}

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