Frage

I need to save some data to the database through AJAX when a form is submitted, and then resume the default action of the form and submit it to PayPal. When done this way, the data is successfully saved in the database, but the form does not submit further.

$('#saveBeforePay').on('submit', function(e){
    e.preventDefault();
    $.post('ajax/save-cart', $(this).serialize())
    .done(function(response){
        if ( response == 200 ) {
            return true;
        }
    });
});

Another way I tried is this

$('#saveBeforePay').on('submit', function(e){
    $.post('ajax/save-cart', $(this).serialize())
    .done(function(response){
        if ( response != 200 ) {
            e.preventDefault();
        }
    });
}); 

Now the form submits but the data does not save to the database. I get this info from the network tab

Request Headers CAUTION: Provisional headers are shown And the Status Text is Canceled

What is wrong here ?

EDIT: Working code

$('#saveOrder').on('click', function(e){
    e.preventDefault();
    var token = $('.token').val();
    $.post('ajax/save-cart', {token: token})
    .done(function(response){
        if ( response == 200 ) {
            $('#saveBeforePay').submit();
        }
    });
});
War es hilfreich?

Lösung

What I usually do with something like this is have a anchor tag in the form and bind the initial event to that rather than the forms onsubmit

$('a#submit').on('click', function () {
    $.post('foo', {}).done(function () {
         $(this).closest('form').trigger('submit');
    });

});

This way you arent preventing the normal form execution, so you can just call the submit event when you want to use it.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top