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.
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">
One way to stop form submission is to return false from your JavaScript function.
We use the preventDefault() method with this event to prevent the default action of the form, that is prevent the form from submitting.
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.
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.
A good way of handling this:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With