JQuery: prevent events defined in AjaxComplete to bind (and fire) multiple times

I ran into a problem with the ajaxComplete()jQuery function (last). Here's the scenario: The form is displayed in a lightbox so that users can enter a delivery address. The submit button for this form is bound to a function in the ajaxComplete()script section (since the form itself is loaded using Ajax). Form data is sent to the server through Ajax. If the data entered by the user is incomplete / invalid, an error message is displayed and the user can transfer it to another. The problem is that every time he does this, the function.done()Ajax is executed several times, exponentially: once the first time, then twice, then 4 times, etc. I suppose this happens because every time an Ajax call is made and completed (for example, the submit form), the event is attached a second time, then these 2 events are connected again, which makes them 4 of them: - (

Here's the code snippet:

$(document).ajaxComplete(function() {
    $('#frm_create_address').submit(function(event) {
        var formData = $('#frm_create_address').serialize();

        $.ajax({
            type        : 'POST',
            url         : '/ajax_results.asp?doIT=checkoutCreateAddress',
            data        : formData,
            dataType    : 'text',
            encode      : true
        })

        .done(function(data) {
            alert("Answer: " + data);
        })
        .fail(function(jqXHR, textStatus) {
            alert("error: " + textStatus);
        });

        return false;
    });
});

I am here with a loss ... What would be the best way to prevent a function from being repeatedly triggered .done()?

In fact, it’s best to ask the following questions: what is the best way to prevent multiple event binding from sending: - /

Thanks in advance for your help! Chris

+4
source share
2 answers

Install global: falseajax in your function.

global ( : true)
:
Ajax . true. false, , ajaxStart ajaxStop . Ajax.

0

, off

$(document).ajaxComplete(function() {
var form = $('#frm_create_address');
form.off('submit', submitListener);
form.on('submit', submitListener);
});

function submitListener(event) {
event.preventDefault();
var formData = $('#frm_create_address').serialize();

$.ajax({
    type        : 'POST',
    url         : '/ajax_results.asp?doIT=checkoutCreateAddress',
    data        : formData,
    dataType    : 'text',
    encode      : true
})

    .done(function(data) {
        alert("Answer: " + data);
    })
    .fail(function(jqXHR, textStatus) {
        alert("error: " + textStatus);
    });

return false;
}
0

Source: https://habr.com/ru/post/1607061/


All Articles