Reputation: 25
How do I add a loading bar while push a linking button with a "href" directed to another page?
Because the backend service needs to process some requests which could take around 10 secs prior to showing the new page. (The situation is when I push the linking button, the page looks like stopping response around 10 secs...)
I need to fire the loading bar action when pressing the linking button.
just found a way using ajaxstart, ajaxstop (ref: http://jsfiddle.net/jonathansampson/VpDUG/170/), is it suitable for my case?
Upvotes: 2
Views: 483
Reputation: 111316
If you're not already using AJAX to load the page in the first place but just a simple <a href="other-page">link</a>
(and from your question I assume that is the case - if I am mistaken then see the answer by sharethis who explains how to do it if you in fact do load the other page using AJAX) then binding handlers to AJAX events won't do what you need since there will be no AJAX events.
I would suggest writing something like this:
function loading () {
$('body').addClass('loading');
setTimeout(function () {
$('body').removeClass('loading');
}, 20000);
}
and binding that function to click handlers for the links that are loading slowly, but without preventing the default link behavior (ie. actually following the link) like this for links with class="slow"
:
$('a.slow').click(loading);
or for every link:
$('a').click(loading);
The setTimeout
is there so in the case when the server doesn't respond for some reason then the user won't have the page unusable forever.
I would still recommend not making the page unusable while the loading spinner is displayed so the user is free to something else while or instead of waiting for the server to respond but that is up to you. See THIS DEMO (your fiddle with some changes in CSS) to see what I mean.
Upvotes: 0
Reputation: 34175
Yes, AJAX is suitable in your case. I will explain it a bit.
After the user clicked on a link, prevent the page loading using JavaScript. In jQuery code this would look like to following.
$('a').click(function(e){
e.preventDefault();
// save the destination of the link for the ajax request
var destination = $(this).attr('href');
});
Display a loading bar.
$('#loading').show();
Then send an AJAX request to the server.
The server receives the request, calculates the result and sends it back to the client.
When the JavaScript on the client side got the response from the server, replace the content of the page. jQuery allows you to define a callback function which is executed when the response arrives.
In case hide the loading bar.
$('#loading').hide();
I recommend using jQuery to do simplified AJAX request. It will save you much time.
Upvotes: 1