Skip to content Skip to sidebar Skip to footer

.submit Doesn't Work If The Bind Object Was Refreshed By Ajax

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 comme

Solution 1:

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

Solution 2:

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() { ... } );
}

Post a Comment for ".submit Doesn't Work If The Bind Object Was Refreshed By Ajax"