Reputation: 11880
Long story short:
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
Reputation: 95022
Your [2] part needs to happen directly on the form.
$("#theForm")[0].submit()
This will bypass the jQuery bound event.
Upvotes: 3