Reputation: 173
Apologies for posting on a question which has already been asked multiple times on SO, but I have been through many of these and still cannot solve my own problem.
I have an index page, 'index.php' with a JQuery script which is intended to post an ID number to 'delete.php', in the same directory. 'delete.php' should then delete the row matching that ID number from a MySQL database. 'index.php' should also remove the deleted item from the HTML.
The last bit, removing the item from the HTML, works, but although I get a "200 OK" response in the error console, 'delete.php' does nothing - I have put in checking echo statements and do not run.
CODE index.php:
<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"> </script>
<script>
jQuery(document).ready(function(){
$(".deleteitem").click(function(){
var parent = $(this).closest('tr');
var id = parent.attr('id');
$.ajax({
type: "POST",
URL: "delete.php",
data: "id=" +id,
success: function(data){
$('#'+id).remove();
}
});
});
});
</script>
</head>
<body>
<table>
<tr id="1">
<td>Milk</td>
<td>3.99</td>
<td><button class="deleteitem"><img src="deletebutton.gif"></button></td>
</tr>
<tr id="2">
<td>Bread</td>
<td>1.99</td>
<td><button class="deleteitem"><img src="deletebutton.gif"></button></td>
</tr>
</table>
</body>
</html>
delete.php:
<?php
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("tryit") or die(mysql_error());
$id = $_POST[id];
echo "DELETE.PHP HAS RUN<br>";
echo "ID = $id";
if (isset($id)) {
$query = "DELETE FROM tryit WHERE id = '$id'";
mysql_query($query) or die('Error, query failed');
}
?>
Any clue as to why this isn't working much appreciated - this is doing my nut in!
Upvotes: 0
Views: 956
Reputation: 173
SOLVED:
The problem was not in the jquery (with the exception of the case sensitivity of 'url:', which was a typo).
The problem was just in the sql query. I had
$sql = "DELETE * FROM tryit WHERE id = '$id'";
whereas of course it should have been
$sql = "DELETE FROM tryit WHERE id = '$id'";
(with no *).
Upvotes: 0
Reputation: 5245
Try
$.ajax({
type: "POST",
url: "delete.php",
data: {id: id},
success: function(data){
$('#'+id).remove();
}
});
url should be lowercase!
Upvotes: 0
Reputation: 42450
In your PHP script, instead of $_POST[id]
, you need to do $_POST['id']
.
As for data, jQuery expects either an object or a query string. You're passing a query string so that should be fine.
Upvotes: 1