1

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?

1
  • Tried $("#theForm").submit(function(e) { e.preventDefault(); /*code*/ ? More info about return false vs preventDefault at stackoverflow.com/a/1357151/684932 Commented May 17, 2013 at 17:32

1 Answer 1

3

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

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

This will bypass the jQuery bound event.

Sign up to request clarification or add additional context in comments.

2 Comments

In the error console, I get "TypeError: $(...)[0].submit is not a function".
Change the name/id of your submit button to something other than submit.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.