.submit doesn't work if the bind object was re

2019-09-17 21:31发布

问题:

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?

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



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