Blue Sky
Blue Sky

Reputation: 1

Submit form values with jquery works but unable to submit standard html form after success

I first want to post some ajax data for a insert in database, this works fine, but submit of standard html form fails with: $("#foo").submit(); The console message loops endless :-/

<script type="text/javascript"> 
// variable to hold request var request; 
// bind to the submit event of our form $("#foo").submit(function(event){
    // abort any pending request
    if (request) {
        request.abort();
    }
    // setup some local variables
    var $form = $(this);
    // let's select and cache all the fields
    var $inputs = $form.find("input, select, button, textarea, text, hidden");
    // serialize the data in the form
    var serializedData = $form.serialize();

    // let's disable the inputs for the duration of the ajax request
    $inputs.prop("disabled", true);

    // fire off the request to /form.php
    request = $.ajax({
        url: "/insert_payment_data.php",
        type: "post",
        data: serializedData
    });

    // callback handler that will be called on success
    request.done(function (response, textStatus, jqXHR){
        // log a message to the console         
    console.log("Hooray, it worked!");
    $("#foo").submit();
});

    // callback handler that will be called on failure
    request.fail(function (jqXHR, textStatus, errorThrown){
        // log the error to the console
        console.error(
            "The following error occured: "+
            textStatus, errorThrown
        );
    });

    // callback handler that will be called regardless
    // if the request failed or succeeded
    request.always(function () {
        // reenable the inputs
        $inputs.prop("disabled", false);
    });

    // prevent default posting of form
    event.preventDefault(); });

</script>

This have been driving me crazy :-(

Upvotes: 0

Views: 203

Answers (1)

Laurent S.
Laurent S.

Reputation: 6946

It's normal :

$("#foo").submit();

This line at the end of your request.done method is triggering the submit of the form, which is probably triggering the AJAX request , which is triggering the request.done ... and so on infinitely :-)

What I would do (try) is remove that line, and also remove the event.preventDefault(); statement you've got at the bottom, so that your submit will simply run as usual after you did your AJAX request.

Upvotes: 1

Related Questions