简体   繁体   中英

JQuery AJAX: Form submits twice

In my form I'm using ajax to submit the form. When I click submit button it executes the method twice. Can someone guide me to find out the problem

$("form#dealForm").submit(function(event){

    //disable the default form submission
    event.preventDefault();

    var $form = $(event.target);

    //grab all form data
    var formData = new FormData($(this)[0]);

    $.ajax({
        url: $form.attr('action'),
        type: 'POST',
        data: formData,
        async: false,
        cache: false,
        contentType: false,
        processData: false,
        success: function (returndata) {
            alert(returndata.message);
        }
    });

    return false;
});

html:

<form name="dealForm" id="dealForm" action="<?php echo base_url(); ?>deals/update_deal/" method="POST" enctype="multipart/form-data">

Try this, if it works, the form is hooked to "submit" twice:

$("form#dealForm").unbind('submit').submit( ...

This will unbind submit, then bind your action. Just a fix if the form is already bound to submit. It is one of many possibilities, likely due to calling your script twice or perhaps your validation plugin binding the submit event separately.

Note: This can potentially unhook your validation plugin, or any other scripts bound to submit.

If this does fix the problem for you, you should investigate why it is happening. Then fix that, and remove the unbind command. It may fix this problem, but it may also cause more problems later. (AKA: Only use this for debugging)

This might not be your problem, but here is something to check.

One thing that causes this sort of problem is if you have injected the html/js into the DOM, whether via ajax or whatever. For example, if you have a button on your page that injects some html form code + js into a div, and then displays it in a dialog for the user to complete -- that sort of thing.

When you click the submit button the first time, the js will process once and then stop (therefore, one ajax submission). However, the next time the user fills out the form and clicks submit, it will process/submit twice. Next time three. etc. I've run into this a number of times. Solution is to move the js .click or .submit event out of the injected code.

As I said, probably not what you are experiencing, but worth knowing about.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM