Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
55
rated 0 times [  59] [ 4]  / answers: 1 / hits: 16668  / 12 Years ago, mon, march 4, 2013, 12:00:00

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.


More From » jquery

 Answers
15

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.


[#79859] Saturday, March 2, 2013, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
trayvon

Total Points: 35
Total Questions: 117
Total Answers: 88

Location: Guernsey
Member since Tue, Jul 6, 2021
3 Years ago
;