Long story short:
- I have an HTML form, with a jQuery function attached to the onSubmit event.
- 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?