user6501471
user6501471

Reputation:

How to stop a form from submitting until an ajax function, that was called by onSubmit, has finished

My code is below. I want the form to submit until after the ajax function has finished, that way the submit variable can be set properly. But submit always has the defaulted false value. How do I get the form to wait until the ajax call is completed and the submit variable is given a new value?

$("#CreateCandidateForm").on('submit', function (event) {
    var theFirstName = $("#FirstName").val();
    var theLastName = $("#LastName").val();
    var submit = false;

    $.ajax({
        type: "POST",
        url: "CreateSearch", // the method we are calling
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify({ firstName: theFirstName, lastName: theLastName }),
        dataType: "json",
        success: function (result) {
            if (result == false) {
                submit = true;
            }                     
        },
        error: function (exception) {
            event.preventDefault();
            console.log(exception);
            alert('Exception: ' + exception);        
        }
    });    
    return submit;
});

Upvotes: 1

Views: 1534

Answers (3)

Kawsar Hamid
Kawsar Hamid

Reputation: 514

jQuery.when() Provides a way to execute callback functions based on zero or more objects, usually Deferred objects that represent asynchronous events.

It will set the submit = true when the ajax requests is successful.

$.when( $.ajax({

          type: "POST",
          url: "CreateSearch", 
          contentType: "application/json; charset=utf-8",
          data: JSON.stringify({ firstName: theFirstName, lastName: theLastName })

       })).then( 

           function(result ){ // Success function
             if (result == false) {
                 submit = true;
             }

           },function(exception){ // failure function
                event.preventDefault();
                console.log(exception);
                alert('Exception: ' + exception);  
         });

Upvotes: 1

Simon
Simon

Reputation: 794

Just always return false;. This will always prevent the submit.

You can then submit it in the success callback:

success: function (result) {
    if (!result) {
        $(this).unbind('submit').submit();
    }                     
}

Don't forget to unbind the submit to prevent an infinite loop.

You should also remove the event.preventDefault() since you don't need it anymore.

Upvotes: 0

Stav Bodik
Stav Bodik

Reputation: 2134

Hi as i understood you need the submit set to true only when you get response from the server inside the result function , jQuery now defines a 'when' function for this purpose.

You may see the full answer in this question and use it for your ajax request :

Wait until all jQuery Ajax requests are done?

 $.when(ajax1()).done(function(a1){
  //a1 includes ajax1 response
    submit=true;
 });

 function ajax1() {
  return $.ajax({
    url: "someUrl",
    dataType: "json",
    data:  yourJsonData,            
    ...
  });
 }

Upvotes: 0

Related Questions