Reputation: 776
I am trying to delete some records from a database table through PHP without the page being reloaded (using AJAX). First I am printing all the information in a table and then the user can click a delete
button, which will delete the record. However, I am having troubles with passing the record id
to the AJAX method.
ListProducts.php
create connection
...
$result = mysqli_query($conn, $sql);
echo "<table border = '1' style = 'border-collapse:collapse;'>";
echo "<tr><th>UserID</th><th>Username</th><th>Action</th></tr>";
if (mysqli_num_rows($result)>0){
while ($row = mysqli_fetch_assoc($result)){
echo "<tr><td>".$row['id']."</td><td>".$row['username']."</td><td><input type = 'submit' onclick = 'delete_record()' value = 'Delete' id = '".$row['id']."'></td></tr>";
}
}
Then, within the same page, there is the AJAX function. I have given each input
field the corresponding id and I am trying to pick it with jQuery
function delete_rekord(){
var id = "Default";
$(document).ready(function(){
$("input").click(function(){
id = $(this).attr('id');
});
});
alert(id); //Test; will print DEFAULT
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function (){
if (this.readyState == 4 && this.status == 200){
alert("Deleted user with ID: " + this.responseText);
}
}
xhttp.open("GET", "delete.php?id="+id, true);
xhttp.send();
}
Over at delete.php
I just delete the record and print the id of the deleted record which I collect in this function as a responseText and print out a message. I have put a test alert(id)
and it seems that the value of var id
is
staying default, just as I initialize it. So the mistake must be in the way I am retrieving the id through jQuery. Any ideas how to resolve this?
Thanks
Upvotes: 0
Views: 225
Reputation: 2328
Pass the value of Id as function parameter
<input type ='submit' onclick = 'delete_record(".$row['id'].")' value = 'Delete' id = '".$row['id']."'>
function delete_record(id){
alert(id);
}
Upvotes: 1
Reputation: 3981
You should pas the id
variable into the delete function
echo "<tr><td>".$row['id']."</td><td>".$row['username']."</td><td><input type='submit' onclick='delete_record(".$row['id']."); return false;' value = 'Delete' id = '".$row['id']."'></td></tr>";`
in your js
function delete_record(id){ // also rename it to delete_record your fn name was delete_rekord
alert(id); //Test; will print the correct ID
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function (){
if (this.readyState == 4 && this.status == 200){
alert("Deleted user with ID: " + this.responseText);
}
}
xhttp.open("GET", "delete.php?id="+id, true);
xhttp.send();
}
Upvotes: 2
Reputation: 389
pass the $row['id'] into your javascript function like below. In your html change the code as below
<input type = 'submit' onclick = 'delete_record(".$row['id'].")' value = 'Delete' id = '".$row['id']."'>
In your javascript, change the function like this
function delete_rekord(rowid){
var id = rowid;
Hope this helps you
Upvotes: 1