who-aditya-nawandar
who-aditya-nawandar

Reputation: 1342

replacement for async:false in $.ajax

I have a form that submits data to the database and then gets submitted to google docs. I am using jquery ajax to achieve this. javascript:

              var name ="a";
              var company = "b";
              var phone = "1";
                ...

              $.ajax({
                    async: false,
                    url: "view/templates/includes/abc.php",
                    //type: 'POST',
                    //timeout: 10000,
                    data: {
                          "name": name,
                          "company": company,
                          "phone": phone,
                          "email": email,
                          "comments": comments
                    },
                    success: function(data) {
                          //called when successful
                          alert(data);
                          //alert('success');
                          $('#php-code').html(data);
                    },
                    error: function(e) {
                          //  alert(e.message);
                          //called when there is an error
                          //console.log(e.message);
                    }
              });
              return true;
        }

abc.php is where lies my code to insert data into the DB.

Now the issue is I don't wanna use async:false since I read it should never be used because it may cause browser hangs and it destroys the purpose of using ajax. However, if I dont use async:false the form gets submitted before my ajax response comes and so it always goes to the error function.

What could I do to not to use async:false?

Upvotes: 1

Views: 880

Answers (1)

Akshay
Akshay

Reputation: 3866

You may calling ajax function on submit.

You may want to stop submitting form at your event(click of button may be).

And in the ajax success method, explicitly submit the form. (can be done using jQuery - $('#id_of_form').submit())

EX. can follow the steps,

$('#id_button_submit').click(function(event){
// this will prevent form to be submitted
             event.preventDefault();
              // call the function of ajax 
              serviceCall();
          });

In the success method of ajax

success: function(data) {
         $('#id_of_form').submit();
         // rest of your code
},

Or A jQuery plugin http://malsup.com/jquery/form/#ajaxSubmit may be useful to you

Upvotes: 1

Related Questions