Skip to content Skip to sidebar Skip to footer

Prevent Ajax Form From Submitting Twice?

I can't figure out why this AJAX form is processing and sending out an email twice. Is there some sort of obvious hickup in the code you can see causing this to occur? HTML

Solution 1:

If to remove all non relevant to the issue code from your snippets we will get the following:

HTML

<formclass="submit-form"method="post"><inputtype="url"name="content_link" /><inputtype="email"name="email" /><button>Send</button></form>

JavaScript

$(function() {
    varEXAMPLE = {
        processSubmitModal : function () {
            var form = $('.submit-form'),
                content_link = $('.submit-form input[type="url"]'),
                email = $('.submit-form input[type="email"]');

            form.submit(function () {
                $.ajax({
                    url: document.location.href,
                    type: 'POST',
                    data: {
                        content_link: content_link.val(),
                        email: email.val()
                    },
                    success: function () { // <-- The function that is executed twice// Do something
                    }
                });
                returnfalse;
            });
        }
    };
    EXAMPLE.processSubmitModal();

    // And somewhere in the code that was not presented in snippet...EXAMPLE.processSubmitModal();
});

I played around with your snippet and it always performs only one AJAX call and process email once except the only case - when somewhere in the code you call EXAMPLE.processSubmitModal() once again. Search in your code, I'm almost sure it is the reason. Pay attention that each time you call EXAMPLE.processSubmitModal() you add one another handler to submit event of the form and not override it.

Solution 2:

Try like this

form.submit(function (event) {

if(event.handled !== true)
  {
//put your ajax codeevent.handled = true;

}
returnfalse;
});

Refernce

Post a Comment for "Prevent Ajax Form From Submitting Twice?"