tags:

views:

40

answers:

4

Hi,

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 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

+1  A: 

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.

fehays
right. I would think you'd want to just re-load the DIV the contains the comments. otherwise, why use AJAX?
dave thieben
Yes you're right, I just want to reload the comment html bit
jul
A: 

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

Scott Evernden
+3  A: 

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 
    }
Daniel Dyson
I need to reload the whole comment html bit, because it also shows the number of comments
jul
You could decrease that by one maybe?
Daniel Dyson
+1  A: 

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;
});
kevingessner
+1 for your comment... async: false // NB: this is usually a bad idea.
Daniel Dyson