jQuery Submitting form Twice
Asked Answered
M

7

11

I know this question has been answered a few hundred times, but I have run through a load of the potential solutons, but none of them seem to work in my instance.

Below is my form and code for submitting the form. It fires off to a PHP script. Now I know the script itself isn't the cause of the submit, as I've tried the form manually and it only submits once.

The 1st part of the jQuery code relates to opening up a lightbox and pulling values from the table underneath, I have included it in case for whatever reason it is a potential problem.

jQuery Code:

$(document).ready(function(){
    $('.form_error').hide();
    $('a.launch-1').click(function() { 
        var launcher = $(this).attr('id'),
            launcher = launcher.split('_');
        launcher, launcher[1], $('td .'+launcher[1]);
        $('.'+launcher[1]).each(function(){
            var field = $(this).attr('data-name'),
                fieldValue = $(this).html();
            if(field === 'InvoiceID'){
                $("#previouspaymentsload").load("functions/invoicing_payments_received.php?invoice="+fieldValue, null, function() {
                    $("#previouspaymentsloader").hide();
                });
            } else if(field === 'InvoiceNumber'){
                $("#addinvoicenum").html(fieldValue);
            }
            $('#'+field).val(fieldValue);
        });
    });
    $("#addpayment_submit").click(function(event) {         
        $('.form_error').hide();  
        var amount = $("input#amount").val();  
        if (amount == "") {  
            $("#amount_error").show();  
            $("input#amount").focus();  
            return false;
        }
        date = $("input#date").val();  
        if (date == "") {  
            $("#date_error").show();  
            $("input#date").focus(); 
            return false;
        } 
        credit = $("input#credit").val(); 
        invoiceID = $("input#InvoiceID").val(); 
        by = $("input#by").val(); 
        dataString = 'amount='+ amount + '&date=' + date + '&credit=' + credit + '&InvoiceID=' + invoiceID + '&by=' + by;
        $.ajax({
            type: "POST",
            url: "functions/invoicing_payments_make.php",
            data: dataString,
            success: function(result) {
                if(result == 1){                    
                    $('#payment_window_message_success').fadeIn(300);
                    $('#payment_window_message_success').delay(5000).fadeOut(700);
                    return false;
                } else {
                    $('#payment_window_message_error_mes').html(result);
                    $('#payment_window_message_error').fadeIn(300);
                    $('#payment_window_message_error').delay(5000).fadeOut(700);
                    return false;
                }
            },
            error: function() {
                $('#payment_window_message_error_mes').html("An error occured, form was not submitted");
                $('#payment_window_message_error').fadeIn(300);
                $('#payment_window_message_error').delay(5000).fadeOut(700);
            }
        });
        return false;
    });
});

Here is the html form:

<div id="makepayment_form">
  <form name="payment" id="payment" class="halfboxform">
    <input type="hidden" name="InvoiceID" id="InvoiceID" />
    <input type="hidden" name="by" id="by" value="<?php echo $userInfo_ID; ?>" />
    <fieldset>
      <label for="amount" class="label">Amount:</label>
      <input type="text" id="amount" name="amount" value="0.00" />
      <p class="form_error clearb red input" id="amount_error">This field is required.</p> 
      <label for="credit" class="label">Credit:</label>
      <input type="text" id="credit" name="credit" />
      <label for="amount" class="label">Date:</label>
      <input type="text" id="date" name="date" />
      <p class="form_error clearb red input" id="date_error">This field is required.</p>
    </fieldset>
    <input type="submit" class="submit" value="Add Payment" id="addpayment_submit">
  </form>
</div>

Hope someone can help as its driving me crazy. Thanks.

Marchpast answered 4/4, 2013 at 23:58 Comment(2)
Try changing it to this $("#makepayment_form").submit(function(event) { event.preventDefault(); leave your submit button in tact.Snuffle
Attempted change to the above, but it did the same thingStumpage
M
48

Some times you have to not only prevent the default behauviour for handling the event, but also to prevent executing any downstream chain of event handlers. This can be done by calling event.stopImmediatePropagation() in addition to event.preventDefault().

Example code:

$("#addpayment_submit").on('submit', function(event) {
  event.preventDefault();
  event.stopImmediatePropagation();
});
Morse answered 8/9, 2013 at 7:42 Comment(2)
This works, but it seems like a cop out... It seems like there is still probably some bad code somewhere and this just adds a fix on top of the issue, instead of fixing the issue.Kasey
Worked great, thanks! I have to admit that it worked fine with just $('form').submit() on localhost but on the server it submitted the form twice. Thumbs up!Gifu
Y
6

Also, you're binding the action to the submit button 'click'. But, what if the user presses 'enter' while typing in a text field and triggers the default form action? Your function won't run.

I would change this:

$("#addpayment_submit").click(function(event) {
    event.preventDefault();
    //code
}

to this:

$("#payment").bind('submit', function(event) {
    event.preventDefault();
    //code
}

Now it doesn't matter how the user submits the form, because you're going to capture it no matter what.

Yoga answered 5/4, 2013 at 0:29 Comment(4)
+1 "Now it doesn't matter how the user submits the form..." :)Rondo
This still resulted in the form being submitted twice :(Stumpage
Well I'm trying to figure out based on the code sample above exactly how the form is submitting twice, but if you are doing the event.preventDefault() and returning false there should not be a problem. Try hiding or disabling the submit button immediately after the event.preventDefault() just in case the user double-clicks. Then, after the successful ajax post, do something like redirect them to a thank you page. Other than that, try debugging with Firebug and see what's going on.Yoga
For some reason I don't understand, I didn't need the event.preventDefault(); line for the .keyup functionAbscission
S
2

Try adding the following lines.

event.preventDefault(); 
event.stopImmediatePropagation();

This worked for me.

Sharondasharos answered 30/1, 2015 at 12:30 Comment(0)
P
2

while all the listed solutions are valid, in my case, what what causing my multiple form submission was the e i was passing to the function called on submit.

i had

$('form').bind('submit', function(e){
  e.preventDefault()
  return false
})

but i changed it to

$('form').bind('submit', function(){
  event.preventDefault()
  return false;
})

and this worked for me. not including the return false should still not stop the code from working though

Precontract answered 15/2, 2021 at 10:33 Comment(0)
S
0

Underneath your click function, add a preventDefault() to the event.

$("#addpayment_submit").click(function(event) {
    event.preventDefault();
    // Code here
    return false;
});

This may solve your problem. preventDeafult() stops the default event from triggering. In this case, your form is triggering when clicked on, then triggering again when you send it using your ajax function.

It also helps to add return false; at the end of the click function (see above).

Snuffle answered 5/4, 2013 at 0:7 Comment(1)
I was thinking the same thing. But the form doesn't have an action tag, so if it submits by itself it will send to the current page, not the AJAX script. And the click function does end with return false; (easier to see now that I've reformatted it).Rhody
C
0

As you are using AJAX request to send data to the server there's no reason even to use form tag and <input type="submit" .../> (you can use simple button instead). Also I think Cumbo's answer should work. If it doesn't you can also try event.stopPropagation().

Clothier answered 5/4, 2013 at 0:14 Comment(0)
M
0

I ended up changing the script upon the recommendations of @user2247104 unfortunately the form still submitted twice.

However @Cumbo, @Barmar were also on the right track, except that to get it to work

event.preventDefault();

Needed to be placed at the bottom of the script:

});
event.preventDefault();
return false;

Thanks to all for their help :)

Marchpast answered 5/4, 2013 at 1:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.