user0103
user0103

Reputation: 1272

Bootstrap button loading + Ajax

I'm using Twitter Bootstrap's button loading state (http://twitter.github.com/bootstrap/javascript.html#buttons).

HTML:

<input type="submit" class="btn" value="Register" id="accountRegister" data-loading-text="Loading..."/>

JS:

(function ($, undefined) {
    $("#accountRegister").click(function () {
        $(this).button('loading');
        $.ajax({
            type:"POST",
            url:"/?/register/",
            data:$("#loginForm").serialize(),
            error:function (xhr, ajaxOptions, thrownError) {
                $("#accountRegister").button('reset');
            },
            success:function (data) {
                $("#accountRegister").button('reset');
            }
        });
        return false;
    })
})(jQuery);

But if I have many buttons I need to write many functions (?). Of course I can make something like this:

$(".ajax-button").bind("click", function() { 
     $(this).button("loading");})

And I can use jQuery Ajax event ajaxComplete

$(".ajax-button").bind("ajaxComplete", function() { 
     $(this).button("reset");})

But this way ALL buttons will be set to normal state when any Ajax request completed.

If user will click on button1 and then click on button2 (both buttons are sending Ajax request), they will be set to normal state when first Ajax request is completed. How to determine which button I need to set to a normal state?

Thank you in advance.

UPDATE

All I need is determine which button triggered some action (Ajax request), set it state to loading and when Ajax request will be completed set it state to normal.

Upvotes: 10

Views: 16960

Answers (1)

user0103
user0103

Reputation: 1272

I found solution for my question =) After reading jQuery documentation I wrote this code for my system:

core.js:

(function ($, undefined) {
    $.ajaxSetup({
        beforeSend:function (xhr, settings) {
            if (settings.context != undefined && settings.context.hasClass('btn')) {
                settings.context.button('loading');
            }
        },
        complete:function () {
            this.button('reset');
        }
    });
})(jQuery);

account.js:

(function ($, undefined) {
    $("#accountRegister").click(function () {
        $.ajax({
            context:$(this), // You need to set context to 'this' element
            //some code here
        });
        return false;
    })
})(jQuery);

This works perfectly. Hope that this will be useful for someone.

Upvotes: 9

Related Questions