I'd like to mimic html form behaviour using jquery. When clicking on a button, I want to delete a comment using:
$(".delete_comment").live('click', function() {
var开发者_Go百科 btn = $(this);
var param_delete_comment = btn.attr("href");
$.ajax({
url: '/you/ajax_delete_comment/'+param_delete_comment,
type: 'POST',
async: false
})
return false;
});
The server side processing seems to work (it deletes the comments and return the comment bit of the html), but the comment bit is not reloaded.
The only difference I can see compared to a html form is that the latter has
Content-Type application/x-www-form-urlencoded; charset=UTF-8
in the request headers.
Anybody can help?
Thank you
Jul
Why do you need to reload the page? If the server side code is working and the comment is deleted, just remove the comment from the DOM on the client side, using the remove()
method.
success: function(){
$('comment').remove(); //might need to change the selector here,
//but you should be able to handle that
}
You say that the AJAX call correctly returns the HTML you need, but you don't do anythign with it. Use the success
callback:
$(".delete_comment").live('click', function() {
var btn = $(this);
var param_delete_comment = btn.attr("href");
$.ajax({
url: '/you/ajax_delete_comment/'+param_delete_comment,
type: 'POST',
async: false, // NB: this is usually a bad idea.
success: function(data) {
// data is the HTML returned by ajax_delete_comment; use it, e.g.:
$('#comment').replaceWith(data);
}
})
return false;
});
I think the "return false" at the end of your click event is preventing the form from submitting.
On a side note, why use ajax if you are going to refresh the entire page? Something to think about.
is $(".delete_comment")
a submit button? if so the return false is your problem. Otherwise,
ajax specifically is meant to AVOID page reloads .. Use a form.submit()
call instead
精彩评论