0

I AJAXified commenting system so when Post Comment button is clicked ajax call is made instead of the original form submission. It works fine till I refresh the page with the comment submit button by ajax. Let's say that I only refresh the div that contains the post and comments and the button. After that the ajax is not triggered rather the original way of submitting is used.

The javascript to submit the form looks like

jQuery('document').ready(function($){
    var commentform=$('#commentform'); // find the comment form

    commentform.submit(function(){
//  $('#commentform').submit(function(){

I tried to use $('#commentform') instead of the variable which didn't help.

I tried to assign the commentform variable again after the successful ajax that loads new post. That didn't help either.

Part of the javascript that loads post via ajax

var $ = jQuery.noConflict();

$(document).ready(function() { 
    $(".mhomepage_item").bind("click", function(){ //bind a click event on a class with name = mhomepage_item

    $.ajax({
            type: "POST",
            url: mhomepage.ajax_url,
            data: { 
                action: "get_post", 
                type: $(this).attr('type'), 
                current_post_id: $('#post_container').attr('current_post_id')
                },
            success: function(response) {
                response_from_json = JSON.parse(response);

                $('#content_container').html(response_from_json['html']);
                commentform=$('#commentform');
     }
    });

    // }
});

Could someone suggest how to make the bind to form submit button permanent even after the button is reloaded via ajax?

Radek
  • 13,813
  • 52
  • 161
  • 255

2 Answers2

4

Try event delegate:

$(document).on("submit","#commentform",function(){
    // action to perform after submit intent
});

By using delegated event handler, you can handle dynamically created elements easily without having to do something like rebinding event handler.

You could also bind the event to the body or the closest container that's available when you call the function to avoid bubbling more levels to document. You could also try this in your case:

jQuery(document).ready(function($){
    $('#content_container').on("submit","#commentform",function(){
        // action to perform after submit intent
    });
});

Documentation

Khanh TO
  • 48,509
  • 13
  • 99
  • 115
  • +1 I was about to post my answer just like that. Just a note : `.on()` requires jQuery 1.7+ – JFK Oct 13 '13 at 08:11
  • second note: you could replace `$(document)` by `$("body")` or the closest parent selector of the form. – JFK Oct 13 '13 at 08:15
  • @JFK: actually, `#content_container` is enough. I think – Khanh TO Oct 13 '13 at 08:16
  • Both examples work nicely. Thank you. Could you explain why it didn't work before? I am lost. – Radek Oct 13 '13 at 08:28
  • 1
    @Radek: your code uses direct event handler. The event handler is attached directly to your `#commentform`, when you call `$('#content_container').html`, your DOM objects are replaced with new ones which don't have event handlers. – Khanh TO Oct 13 '13 at 08:31
  • @KhanhTO: could you have a look at my new question? http://stackoverflow.com/q/19371848/250422 It must be similar solution but I cannot figure it out. Maybe I didn't even describe what I want as Sparky didn't understand me.... Thank you – Radek Oct 15 '13 at 04:29
  • @Radek, you've split your question into two postings and left critical information out of the other. Each question should be "self-contained" and not rely on another to make sense. – Sparky Oct 17 '13 at 22:45
  • @Sparky: Not sure what you mean. 1) This was the first question. I didn't know I was going to do validation after I made this question working. 2) what critical information didn't I provide? In case someone wanted more background I pointed out why things must be done certain way. Meaning that I was able to make validation work by myself but then the ajax submit was broken. All this was in the first version of my second question. – Radek Oct 17 '13 at 22:56
  • @Radek, I'm simply referring to two things: 1) that not enough code was provided in the [other question](http://stackoverflow.com/questions/19371848/submithandler-is-not-triggered-although-it-is-valid)... ajax is cut off and concise markup missing. 2) that according to your comments, looking at this question seems to be required in order to fully understand your other question. Oh well, no worries. I'll revisit the other question as time permits. – Sparky Oct 17 '13 at 23:00
  • @Sparky: well I am learning all the time. So I am happy if you point out how I can make my questions better. Directly under this question is request for html sample. The accepted answer didn't need html. I don't understand exactly what is going on and I thought that html is not needed. I still believe that :-) Thank you for helping (me) out .... – Radek Oct 17 '13 at 23:04
  • @Radek, I like to see markup to 1) make sure there are no selecting errors and 2) to make less work for me when I construct a working demo. With what was provided, I can only post an answer with general recommendations. Again, maybe later as time permits. – Sparky Oct 17 '13 at 23:18
0

Accordingly with: jQuery binding click to a link after AJAX call

You must bind a button to click/submit event in success callback.

you can to do:

success: function(response) {
      response_from_json = JSON.parse(response);

      $('#content_container').html(response_from_json['html']);
      commentform=$('#commentform');

      $('#commentform').bind("submit", function() { ... } );
}
Community
  • 1
  • 1
Snake Eyes
  • 16,287
  • 34
  • 113
  • 221