Search code examples
javascriptjqueryajaxajaxform

ajaxSubmit target being duplicated not replaced


I have the following code:

$('#refresh').click(function () {

    alert($('.report-container').length);

    $('.report-container').each(function () {

        var accordian = this;
        var url = $(this).children(':first-child').val();

        $('form').ajaxSubmit({
            url: url,
            success: function (responseText, statusText, xhr, $form) {
                $(accordian).html(responseText);
            }
        });

    });
});

this basically gets each of the tabular reports on the page and refreshes them using the form configured by the user.

i would expect this to replace the one and only '.report-container' element with the fragment downloaded from the server. however each time this is ran the call to alert($('.report-container').length); is incremented?

this is causing all sorts of issues obv - what am i missing?

ftr i have also tried using the target property on the ajaxForm plugin with the same outcome

I can also confirm that the server responds with one and only one '.report-container' in the fragment so it should be a 1 -> 1 replacement.


Solution

  • IF you truly only have one container, and it will be replaced:

    $('#refresh').click(function() {
        var container = $('.report-container');
        var url = container.children(':first-child').val();
        $('form').ajaxSubmit({
            url: url,
            success: function(responseText, statusText, xhr, $form) {
                container.replaceWith(responseText);
            }
        });
    });
    

    IF you wish to expand to more than one, keep/add back the each but cache the select in "accordian":

    $('#refresh').click(function() {
        $('.report-container').each(function() {
            var accordian = $(this);
            var url = accordian.children(':first-child').val();
            $('form').ajaxSubmit({
                url: url,
                success: function(responseText, statusText, xhr, $form) {
                    accordian.replaceWith(responseText);
                }
            });
        });
    });