Reputation: 61737
The aim of this code is to delete a comment with AJAX. The function is called as follows:
DeleteComment(166);
And the code that runs is:
// Each delete button
function DeleteComment(CommentID) {
$.ajax({
url: AJAXURL + "?action=del&id=" + CommentID,
success: function (data) {
// Parse the data
if (data.substring(0, 1) == "1") {
$('#cid' + CommentID).hide();
} else {
alert(data.substring(2, data.length));
}
}
});
}
However the $('#cid' + CommentID).hide();
line never fires as CommentID
isn't retained, I'm new to Jquery, could someone show me how to change this so the comments ID is retained when the ajax success is called?
Upvotes: 0
Views: 331
Reputation: 39017
Can you post more of the surrounding code? As is, your code looks like it should work. But I see a troublesome comment: // Each delete button
. The way you are binding the DeleteComment function to the buttons must not be working the way you assume.
Try this instead:
// Iterate over each delete button.
// The .each(...) provides you a function, a.k.a. local scope, for each button.
$(".deleteButtons").each(function (idx, el) {
// This is very important: you must create a local variable to hold the ID.
// How to get the ID is up to you.
var id = getTheCorrespondingCommentId(idx, el);
// Now you can safely pass the local variable to the DeleteComment function:
$(el).click(function() { DeleteComment(id); });
});
Upvotes: 1
Reputation: 5084
put the $('#cid' + CommentID).hide();
before $.ajax({
and then add $('#cid' + CommentID).show();
to your else condition..
Hide it first and then reshow it if deletion fails...
Not the most graceful solution, but the path of least resistance from where you are.
Upvotes: 1