Bas Verhagen
Bas Verhagen

Reputation: 31

Reloaded DIV content with AJAX and still use AJAX again which is not reloaded

I'm using jQuery AJAX to reload only a DIV content without refreshing the whole page. The new results will shown in the DIV.

Now the problem is that these results have buttons which use jQuery AJAX as well. When the AJAX loads the DIV content, these buttons can't use AJAX again because the AJAX is not reloaded or something like that(?). It only works fine when the whole page is reloaded but that is not what I want.

How can I use AJAX scripts again when the DIV content is reloaded?

jQuery AJAX script to add result and reload only div with results:

$(document).ready(function(){
    $('#form_disabled_date').submit(function(e){
        e.preventDefault();
        var form = $(this);
        var result = $('#disabled_date');
        var post_url = form.attr('action');
        var post_data = form.serialize();
        $.ajax({
            type: 'POST',
            url: post_url,
            data: post_data,
            success: function(msg) {
                $(result).fadeOut(500, function(){
                    result.load(document.URL +  ' #disabled_date').fadeIn();
                });
            }
        });
    });
});

HTML:

<div id="disabled_date">
   result1 (delete), result2 (delete), result3 (delete) <-- results loaded with PHP
</div>

jQuery AJAX for submit delete button and reload only div with results:

$(document).ready(function(){

$('.form_delete_disabled_date').submit(function(e){

    e.preventDefault();
    var form = $(this);
    var result = $('#disabled_date');
    var post_url = form.attr('action');
    var post_data = form.serialize();

    $.ajax({

        type: 'POST',
        url: post_url,
        data: post_data,
        success: function() {

            $(result).fadeOut(500, function(){
                result.load(document.URL +  ' #disabled_date').fadeIn();
            });

        }

    });

});

});

The results are add by a form with id: "form_disabled_date". The div "disabled_date" is reload with the JavaScript code above. the delete buttons had class: "form_delete_disabled_date".

How can I reload the div content and still use jQuery which is not reloaded?

SOLUTION: I had to change the following code:

$(document).ready(function(){

  $('.form_delete_disabled_date').submit(function(e){
    //code
  });
});

To:

$(document).on('submit', '.form_delete_disabled_date', function(e){
    //code
});

Now the submit event is bind to "form_delete_disabled_date" when the AJAX reloaded the div but not the page. The new results can use the code now.

Upvotes: 0

Views: 81

Answers (0)

Related Questions