Steve Perkins
Steve Perkins

Reputation: 11880

Making a jQuery AJAX call from within a form submit function

Long story short:

  1. I have an HTML form, with a jQuery function attached to the onSubmit event.
  2. Inside of that onSubmit function, I need to make an AJAX call, and update a form element based on the response.

Sample code:

$("#theForm").submit(function() {
    $.ajax({
        url: theUrl,
        type: "POST",
        data: theData
    }).done(function(theResponse) {
        $("#someInput").val(theResponse)
        $("#theForm").submit()  // [2] Submit the form now
    }).fail(function(jqXHR, textStatus) { 
        alert("Failure") 
    })
    return false  // [1] Prevent submission prior to AJAX call completing
})

My problem is that this creates an infinite loop.

The outmost layer of this function returns false, to prevent the form submitting prior to the AJAX call finishing. I am trying to actually submit the form within the done() handler, after the AJAX call successfully completes. However, this just invokes the overall onSubmit function recursively.

How can I have an AJAX call nested within an onSubmit handler... such that decision on whether to allow the submit is driven by the nested AJAX function, rather than its enclosing handler function?

Upvotes: 1

Views: 1128

Answers (1)

Kevin B
Kevin B

Reputation: 95022

Your [2] part needs to happen directly on the form.

$("#theForm")[0].submit()

This will bypass the jQuery bound event.

Upvotes: 3

Related Questions