Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preventing submit until ajaxes are done

I'm using jQuery, and I'd like to make it so that a form submit won't work until all ajax calls have completed.

One way I have thought of doing this would be to store a boolean value which indicates whether there is an ajax request going on. It would be set to false at the end of every one.

I'm not sure if this is the best way though, so I'd appreciate any input.

like image 534
bgcode Avatar asked Jun 04 '11 20:06

bgcode


People also ask

How stop Ajax submit?

If you want to prevent the default post method for the form's submit button, I suggest you could consider using the event. preventDefault() method. More details, you could refer to below codes: <form id="user-form" method="post">

How Stop JavaScript submit?

One way to stop form submission is to return false from your JavaScript function.

How do I stop form submit in jQuery?

We use the preventDefault() method with this event to prevent the default action of the form, that is prevent the form from submitting.

What is jqXHR in Ajax?

The jqXHR Object. The jQuery XMLHttpRequest (jqXHR) object returned by $.ajax() as of jQuery 1.5 is a superset of the browser's native XMLHttpRequest object. For example, it contains responseText and responseXML properties, as well as a getResponseHeader() method.


2 Answers

Rather than use boolean, you should use an integer counter (var i=0;).

i++ every time an AJAX request is made, and

i-- every time an AJAX request is completed.

The benefits of using a counter are that it will allow you to make multiple AJAX requests at a time. With boolean, it is more buggy, because making multiple requests can cause the submit button to unlock before actions are completed.

As for the user interface, you should consider using some sort of 'loading' indicator, to show that it is working. Then, once the counter is back to zero, you can hide the loading indicator and enable the submit functionality.

like image 185
Kranu Avatar answered Oct 05 '22 20:10

Kranu


A good way of handling this:

  • Change your submit button to a normal button
  • Bind a function to the submit button which runs the ajax request
  • Assign the success parameter of the jQuery AJAX request object to submit the form
like image 22
8bitme Avatar answered Oct 05 '22 20:10

8bitme