2

I have a form that submits shopping cart data to a payment gateway (WorldPay) payment processing page. I need to perform a couple of extra logic the moment the custom decides to proceed to the payment but before the form submission itself. Basically, I simply want to generate a unique reference to the order at the very last moment.

Here is the jQuery code for the submit event:

$(function(){

   $('#checkout-form').submit(function(e){

       var $form = $(this);

       var $cartIdField = $('#cartId');

       console.log($cartIdField.val());

       if($cartIdField.val() == ''){

            e.preventDefault();

            $.ajax({
                url: baseUrl + '/shop/ajax/retrieve-shopping-cart-reference/',
                data: {}, type: 'post', dataType: 'json',
                success: function(json){
                    if(json.error == 0){
                        $('#cartId').val(json.data.cart_reference_number);
                        $form.submit();
                    }else{
                        alert(json.message);
                    }
                }
            });
        }else{
            console.log('Submitting form...'); //Does not submit!
        }
   });

});

The problem is that during the second submit triggered within the success: clause, the form isn't submitted still. I am assuming event.preventDefault() persists beyond the current condition.

How can I get around this?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Bez Hermoso
  • 1,132
  • 13
  • 20
  • What's the output from `console.log($cartIdField.val());` on the second submit? – Anthony Grist Jun 22 '12 at 09:32
  • http://stackoverflow.com/questions/1164132/how-to-reenable-event-preventdefault/1168022#1168022 ?? `.trigger('submit')` might help, – Tats_innit Jun 22 '12 at 09:33
  • @Tats_innit That's what this code appears to be doing already, yet still isn't working - I don't think the problem is actually with the `e.preventDefault()`. – Anthony Grist Jun 22 '12 at 09:35
  • @AnthonyGrist I concur, agreed! Hey OP can you please flick a JSfiddle? might be something very small, cheers. – Tats_innit Jun 22 '12 at 09:36
  • or try this `$(this).unbind('submit').submit()` – Tats_innit Jun 22 '12 at 09:39
  • What is being logged by those two `console.log`? – Thomas Jun 22 '12 at 09:41
  • The problem could be around the `$cartIdField.val() == ''` and `$('#cartId').val(...)` lines. Are you sure the value is successfully set in the latter case? – Salman A Jun 22 '12 at 09:47
  • @Shasteriskt: I think your assumption about the problem is wrong. I've tried to replicate something similar to what you do (interrupt form submission with AJAX request then resubmit), and it seems to work: http://jsfiddle.net/foxbunny/xkvHy/ So, e.preventDefault() does NOT persist through subsequent calls to submit(). –  Jun 22 '12 at 10:05
  • It seems to work here too: http://jsfiddle.net/salman/zZv8y/5/ -- earlier I had same problem as you (form not submitting and AJAX request fired over an over again) but realized the error was inside the `if` condition. – Salman A Jun 22 '12 at 10:07
  • I'm assuming you have added a console.log in front of the second submit at some stage to ensure it actualy hits the second submit? Have you also checked the console outputs (using FireBug for Firefox or similar for other browsers) that you have no unexpected errors along the execution paths? – Nope Jun 22 '12 at 10:20
  • Hi guys. Yes, I did check the value for `$cartIdField.val()` via the first console.log line, and it does have a value the second time around. Weirdly enough, it works when I try it on jSFiddle too: http://jsfiddle.net/Y4awV/. :/ – Bez Hermoso Jun 22 '12 at 12:16

3 Answers3

1

For performe the any operation before form submit i used the following menthod hope it wil help

 $('#checkout-form').live("submit",function(event){

    //handle Ajax request use variable response
         var err =false;

         var $form = $(this);
        //alert($form);
        var values = {};
         $.each($form.serializeArray(), function(i, field) {
             values[field.name] = field.value;
        });
     //here you get all the value access by its name [eg values.src_lname]
       var $cartIdField = $('#cartId');

       console.log($cartIdField.val());

       if($cartIdField.val() == ''){
             $.ajax({

                   // your code and condition if condition satisfy the return true
                   // else return false 
                   //   it submit your form
                   /*if(condition true)
                      {
                        var err =true;
                      }
                     else
                      {
                         var err = false;
                       }*/

                 })
        }
        else
        {
           return true;
        }
      if(err)
  {
     return false
  }
 else
 {
   return true;

}
     })
Hardik Raval
  • 1,948
  • 16
  • 29
  • A return inside the ajax success function wouldn't affect if the form gets submitted – Thomas Jun 22 '12 at 09:44
  • How exactly is this going to help? – Salman A Jun 22 '12 at 09:44
  • @SalmanA it use jQuery "live" it attach the current event handler, and then you can manage your form submition with validation and ajax request by "return true and false" – Hardik Raval Jun 22 '12 at 09:51
  • 1
    (i) `.live` or `.submit` won't make a difference here (ii) AJAX requests are asynchronous by default; returning true/false from there and/or setting a condition variable and checking it inside the submit handler will NOT work. – Salman A Jun 22 '12 at 09:59
  • @SalmanA agree with you but handling the Ajax response while form submition , i used way what i suggest in code either use Ajax "asyc:false" , You have any better idea ? then it will help me also – Hardik Raval Jun 22 '12 at 10:05
  • The better idea is to fire or trigger the submit event on AJAX's success; exactly what the OP is doing. – Salman A Jun 22 '12 at 10:10
  • 1
    @hRaval: Don't use `live()` it has been deprecated and has several issues. Use `on()` as of jQuery 1.7. Use `delegate()` if you are on 1.6.x or previous. If you are using jQuery pre 1.4.2 use `bind()`. See documentation for details: http://api.jquery.com/live/ – Nope Jun 22 '12 at 10:24
0

e.preventDefault() remove default form submit attribute which can not be reverted if applied once.

Use below code instead to prevent a form before submitting. This can be reverted.

$('#formId').attr('onsubmit', 'return false;');

And below code to restore submit attribute.

$('#formId').attr('onsubmit', 'return true;');
-1

Only call e.preventDefault() when you really need to:

if(not_finished_yet) {
  e.preventDefault();
}
Thomas
  • 8,426
  • 1
  • 25
  • 49
  • Did you look at the code at all? The `e.preventDefault()` is already inside a condition, then the form gets submitted again when an AJAX request has returned a successful response. – Anthony Grist Jun 22 '12 at 09:32
  • You're right, I didn't notice that `$cartIdField` and `$('#cartId')` are the same. – Thomas Jun 22 '12 at 09:40