Reputation: 145
My question is fairly straight forward. I am creating a table from a mysql table and each row in the table holds records from the database. For each new record a new row is made and so on until there are no more records returned. I want to give them an option to delete a record and so I want to give each row it's own class name and so i am trying to echo php code into the class name.
It looks like this:
<tr class="name<?php echo $row['id'];?>">
Would the class then be name1 if $row['id'] was 1?
Alright so now that I got confirmation on this I am using jQuery to delete the record and not reload the page.
What i am trying to do is when a user clicks a button I use AJAX to delete a record in the db and on the screen. I have it working to delete from the db, but I am having trouble deleting it on the screen without re-loading the page.
Here is my jQuery code:
$(".delete").click(function(){
var delete_id = "delete_id="+$(this).attr("id")
$.ajax({
type: "POST",
dataType: "HTML",
url: "deleteScript.php",
data: delete_id,
success: function(data) {
$(".name"+$(this).attr("id")).remove();
}
});
});
Shouldn't this remove anything with the class name on the screen? I have used alert to make sure that .name"+$(this).attr("id") was right, and it returned what I thought it would. So I am now confused where I went wrong.
Help?
Upvotes: 0
Views: 105
Reputation: 282885
Yes, the class name would be "name1" if $row['id']
is 1. You could have looked at the output HTML to confirm that though.
Also, I'm not sure how this helps you with the deleting records problem. I'd add an extra column to the effect of
<td><a href="/delete-row.php?id=<?=$row['id']?>">Delete</a></td>
And then this is where the fancy-pants-omg-you-have-to-use-POST-guys start screaming, so that should probably take you to a confirmation page where you can use a form with a delete button.
If you're using jQuery, then you should technically be using an "id" instead of a "class" attribute, but I'd still do it this way, and then ajaxify the link so it doesn't take you to another page. This way, it won't explode if the user has JS disabled, they'll just have a slightly use user-friendly way of deleting things.
Upvotes: 1
Reputation: 237865
The problem with your code is in the following line:
$(".name"+$(this).attr("id")).remove();
Since you are inside an AJAX success handler, this
refers to the XMLHTTPRequest object, not to the element on which the event is triggered. You should cache the element for use inside the success handler.
Your code should eventually look like this:
$(".delete").click(function(){
var delete_id = "delete_id="+this.id,
self = this; // cache this
$.ajax({
type: "POST",
dataType: "HTML",
url: "deleteScript.php",
data: delete_id,
success: function(data) {
$(".name"+self.id).remove(); // use self rather than this
}
});
});
Note also that I have used this.id
because it is far, far quicker (20x or more) than $(this).attr('id')
.
Upvotes: 1