Reputation: 10637
I have the following jQuery code:
$.ajax({
type: "POST",
url: "/search",
data: $("form").serialize(),
success: function(data) {
$("#tab").addClass("loading"); // THIS LINE DOESN'T WORK
// . . . LOAD SEARCH RESULTS HERE (USUALLY TAKES SEVERAL SECONDS) . . .
$("#tab").removeClass("loading");
}
});
And I have the following CSS:
.loading {
background: transparent url(../resources/images/loading.gif) no-repeat right center;
text-indent: -1000px;
}
And I have the following relevant HTML:
<div id="tab">
<table id="searchResultsGrid"></table>
</div>
I can't get the line $("#tab").addClass("loading")
to work. Watching in FireBug, the class .loading
is never added to the #tab
object. What am I doing incorrectly?
Thanks!
Upvotes: 1
Views: 1264
Reputation: 412
first you addClass loading ,then you removeClass loading ,that's why you didn't see it working , you should add loading class before the ajax call, when the call returns success, you can removeClass
Upvotes: 0
Reputation: 78630
You should set the class prior to the ajax call and then remove it in the success function. What you are doing is setting it and then removing it in the same code execution. The class will not visually update until the code completes execution, at which point you have already removed the class.
Upvotes: 0
Reputation: 13676
Without seeing the HTML, it's hard to say, but one thing that stands out is that you're adding the class once the ajax call returns with a success. Try changing to this:
$("#tab").addClass("loading");
$.ajax({
type: "POST",
url: "/search",
data: $("form").serialize(),
success: function(data) {
// . . . LOAD SEARCH RESULTS HERE . . .
$("#tab").removeClass("loading");
}
});
Upvotes: 0
Reputation: 63512
Try this instead. What's probably happening is that it's adding and removing the loading
class quickly enough that it steps on itself
// add the class before the ajax call
$("#tab").addClass("loading");
$.ajax({
type: "POST",
url: "/search",
data: $("form").serialize(),
success: function(data) {
// . . . LOAD SEARCH RESULTS HERE . . .
}
complete: function(data) {
// remove the class on complete, not success, in case of an error
$("#tab").removeClass("loading");
}
});
Upvotes: 4