Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 979
user0103 Avatar asked Mar 04 '13 08:03

user0103


1 Answers

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.

like image 149
user0103 Avatar answered Oct 08 '22 22:10

user0103