开发者

jQuery Showing an Ajax loader during transmission & Prevent Multiple Submits

I have an app that has several different types of form elements which all post data to the server with jQuery AJAX.

What I want to do is:

  1. Show a loader during AJAX transmission
  2. Prevent the user from submitting twice+ (clicking a lot)

This is easy to do on a one off basis for every type of form on the site (commen开发者_运维知识库ts, file upload, etc). But I'm curious to learn if that is a more global way to handle this?

Something that's smart enough to say:

  1. If a form is submitting to the server and waiting for a response, ignore all submits
  2. Show a DISABLED class on the submitted / clicked item
  3. Show a loading class on the class="spinner" which is closest to the submit item clicked

What do you think? Good idea? Done before?


Take a look at the jQuery Global Ajax Event Handlers.

In a nutshell, you can set events which occur on each and every AJAX request, hence the name Global Event Handlers. There are a few different events, I'll use ajaxStart() and ajaxComplete() in my code sample below.

The idea is that we show the loading, disable the form & button on the ajaxStart() event, then reenable the form and hide the loading element inside the ajaxComplete() event.

var $form = $("form");
$form.ajaxStart(function() {
     
    // show loading
    $("#loading", this).show();

    // Add class of disabled to form element
    $(this).addClass("disabled");

    // Disable button
    $("input[type=submit]", this).attr("disabled", true);
});

And the AJAX complete event

$form.ajaxComplete(function() {

    // hide loading
    $("#loading", this).hide();

    // Remove disabled class
    $(this).removeClass("disabled");

    // Re-enable button
    $("input[type=submit]", this).removeAttr("disabled");
});

You might need to attach to the ajaxError event as well in case an AJAX call fails since you might need to clean up some of the elements. Test it out and see what happens on a failed AJAX request.

P.S. If you're calling $.ajax or similar ($.getJSON), you can still set these events via $.ajaxStart and $.ajaxComplete since the AJAX isn't attached to any element. You'll need to rearrange the code a little though since you won't have access to $(this).


I believe you have to do 2 for sure and 3 to improve usability of your app. It is better to keep backend dumb but if you have a security issue you should handle that too.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜