Loading Indicator in Ajax - javascript

I know this has been asked and answered many times in this forum. But it does not work in what I am looking for.
I want to display a loading indicator while the ajax div is loading. There are cases when it takes a few minutes to load so it would be good to let the user know that the is loading.
From what I gathered it can be done in jquery. I am not too familiar with jquery yet. With this code the loading works but only for the first page.
$(document).ready(function() {
$('body').append('<div id="ajaxBusy"><p><img src="ajax-loader.gif"></p></div>');
});
$(document).ajaxStart(function(){
$('#ajaxBusy').show();
}).ajaxStop(function(){
$('#ajaxBusy').hide();
});
My page is structured like this
Header Page
-Div (display ajax here)
-Another div within the first loaded page(Load another page through ajax here)
I need it to display the loading indicator in the second div while it's loading. I am assuming that jquery "body" appends it to the main page body once and doesn't run again as it's within the same page. I did try to create a div and instead of body, load the div in jquery but it doesn't work.
Any help will be greatly appreciated.

I found that the easiest way to add the loader gif to specific elements is to create a CSS class with the loader as a background instead of appending an actual image:
.ajax-loader {
background: url(ajax-loader.gif) center center no-repeat;
}
Then you just add that class to the element you are loading and remove it when it is done:
// Removes any loaded images on Ajax success
var removeLoader = function(event, XMLHttpRequest, ajaxOptions)
{
$('.ajax-loader').removeClass('ajax-loader');
};
// Add the ajax loader to a specific element and remove it when successful
$('.div1').addClass('ajax-loader').load('mypage.html', removeLoader);

considering that the div you want to load your image has an id="theDiv"
$(document).ready(function() {
$('#theDiv').append('<div id="ajaxBusy"><p><img src="ajax-loader.gif"></p></div>');
});

Is there a reason you're appending your "ajaxBusy" div via Javascript? Why not just include the HTML on the page itself?
<div id="main">
<div id="ajaxBusy">
<p><img src="ajax-loader.gif"></p>
</div>
</div>
Try binding the ajaxStart and ajaxStop to the ajaxBusy div instead of the document.
$('#ajaxBusy').ajaxStart(function(){
$(this).show();
}).ajaxStop(function(){
$(this).hide();
});

Related

show div while load is executing in jquery

I'm trying to show a div that That indicates that the page is loading, for the load I use the jquery load event, however, the load div always stays on the page and there is no hidden end load, my code is this:
$("#mydiv").fadeIn("fast");
$('#page').load('myphp.php', { 'data': id },function(){
$("#mydiv").fadeOut("fast");
});
Hide the div when the document finishes loading via
$(document).ready(function() {
$("#mydiv").fadeOut("fast");
});
(include this code after the rest of your JS in the header), e.g.
HTML headers
JS/jQuery
this^
CSS link
HTML body contents
you can use $('#page').ajaxStart(callback); and $('#page').ajaxStop(callback);.
look here:
https://api.jquery.com/ajaxStart/
https://api.jquery.com/ajaxStop/

jQuery shows hidden content on refresh

I use this fancy little jQuery toggle on my site, works great. But now I have a little larger text area I want to hide, and therefore I've included it in another php file, but when the site opens\refreshes the content is briefly shown and then hidden? Have I done something wrong or does it simply not work right with includes in it ?
Show me?
<div class="content">
<?php include 'includes/test.php'?>
</div>
<script>
jQuery(document).ready(function() {
var par = jQuery('.content');
jQuery(par).hide();
});
jQuery('#toggleMe').click(function() {
jQuery('.content').slideToggle('fast');
return false;
});
</script>
Use css to hide it
.content{
display:none;
}
Also
var par = jQuery('.content');
is a jQuery object so don't need to wrap it again as
jQuery(par).hide();
Just use par.hide(); but in this case, when you will use css to hide the element, then you don't need this anymore.
That will happen. The document briefly shows all the HTML before executing the code in your ready handler. (It has nothing to do with the PHP include.) If you want an element hidden when the page loads, hide it using CSS.
#myElement {
display: none;
}
The toggle should still work correctly.
You just need to don't use jquery document ready function. just use style attribute.
Show me?
<div class="content" style="display:none">
<?php include 'includes/test.php'?>
</div>
<script>
jQuery(document).ready(function() {
jQuery('#toggleMe').click(function() {
jQuery('.content').slideToggle('fast');
return false;
});
</script>
If this information is sensitive/not supposed to be seen without access granted, hiding it with CSS will not fix your problem. If it's not, you can ignore all of this and just use CSS with a display: none property.
If the information IS supposed to be hidden:
You need to only load the file itself on-demand. You would request the data with AJAX, do a $('.content').html() or .append() and send the result back directly from the server to the browser using something like JSON.
You are using the "ready" function that meant it will hide the element when the document is ready (fully loaded).
You can hide it using css:
.contnet { display: none; }
how you render you site server side does not affect how the site is loaded on the browser, what affects it is how the specific browser chooses to load your javascript and html, what i would recommend is set the element to hidden with css, since that is applied before anything else. And keep you code as is, since the toggle will work anyways
You can also clean up the code a little bit.
<script>
$(document).ready(function(){
$('.content').hide();
$('#toggleMe').click(function(){
$('.content').slideToggle('fast');
});
});
</script>

Wrapping all AJAX calls jQuery

I populate many parts of my website using
$("#theDivToPopulate").load("/some/api/call.php", callBackToBindClickEventsToNewDiv);
Where /some/api/call.php returns a built list, div, or some other HTML structure to place directly into my target div. The internet has been running slow lately and I've noticed that the time between a button click (which kicks off these API calls) and the div populating is several seconds. Is there an easy way to globally wrap all the load calls so that a div containing "Loading..." is displayed before the call is even made and hidden once the API call is complete.
I can not simply put the code to hide the div into the callBackToBindClickEventsToNewDiv as some load events have different call backs. I would have to copy the code into each function which is ugly and defeats the purpose. I want the flow of any .load to go as follows:
1) dispplayLoadingDiv()
2) Execute API call
3) Hide loading div
4) do callback function.
The loading div must be hidden first as the callback contains some animations to bring the newly loaded div in nicely.
EDIT:
Expanding on jacktheripper's answer:
var ajaxFlag;
$(document).ajaxStart(function(){
ajaxFlag = true;
setTimeout(function (e) {
if(ajaxFlag) {
hideAllDivs();
enableDivs(['loading']);
}
}, 500);
}).ajaxStop(function(){
ajaxFlag = false;
var load = $("#loading");
load.css('visibility','hidden');
load.css('display','none');
load.data('isOn',false);
});
This way loading is only displayed if the page takes more than 500 MS to load. I found the loading flying in and out real fast made things kind of choppy for fast page loads.
Use the following jQuery:
$(document).ajaxStart(function(){
$('#loader').show();
}).ajaxStop(function(){
$('#loader').hide();
});
Where you have an element called #loader that contains what you want to show when an AJAX request is being performed. It could be a span with text, an image (eg a gif), or anything similar. The element should be initially set to display: none
You do not even need to call the function anywhere else.
Try this
$("#someButtonId").click(function(e){
e.preventDefault();
$("#theDivToPopulate").html("Loading...");
$.get("/some/api/call.php",function(data){
$("#theDivToPopulate").fadeOut(100,function(){
$("#theDivToPopulate").html(data).fadeIn(100,function(){
//Do your last call back after showing the content
});
});
});
});

How to execute jQuery function after Ajax page load

I'm building Wordpress website where all content pages are loaded using Ajax. This is causing me a problem with jQuery localScroll plugin. This plugin will add animated scroll to all anchor links on the page. Problem is that using script below I'm able to have animation on that page only after one of the links on the page is clicked.
I think I understand why is this happening. My guess is that after I click on the main menu script will execute but since Ajax content is not yet loaded events are not attached to Ajax loaded content links. Now I'm stuck, I have no clue how to fix this. Would you mind helping me with this one?
Thank you in advance.
$(function(){
$('a').live('click', function() {
$('#portfolioWrap').localScroll({// Only the links inside that jquery object will be affected
target: '#portfolioWrap', // The element that gets scrolled
axis:'y', // Horizontal scrolling
duration:1500
});
});
});
EDIT
Just a note to others after I managed to make this work. I tried all suggestions here. My guess is that solutions suggested by o.v. and Ohgodwhy should work, but probably due to website complexity and maybe plugin limitations I wasn't able to make them work. For example .on function didn't work at all although I'm using jQuery 1.7.1. At the end I implemente ajaxComplete suggested by Just_Mad and that worked. Thank you all for your help!
This is the code:
$(function() {
$('#wrapperIn').ajaxComplete(function() {
$('#portfolioWrap').localScroll({
target: '#portfolioWrap', // The element that gets scrolled
axis:'y', // Horizontal scrolling
duration:1500
});
});
});
If you use jQuery.ajax to load AJAX content you can try to bind to ajaxComplete event, to get the moment, when any ajax is complete.
Elaborating on what GoldenNewby said, listen/attach with the .on() method introduced in jQuery 1.7.
$(function(){
$('body').on('click', 'a', function() {
$('#portfolioWrap').localScroll({
target: '#portfolioWrap', // The element that gets scrolled
axis:'y', // Horizontal scrolling
duration:1500
});
});
});
No need to use AJAX for callbacks for listening/binding to elements. The above function will place a click function on all elements found within the body{1} at/after page load. This includes all dynamically created links.
{1} - Change 'body' to whatever Container has the ajax data. I.E. #portfolioWrap
Add a callback to the ajax load, good place to start is at http://api.jquery.com/jQuery.ajax/ under "success callback"
I would have given more specific advice, but your snippet is a bit isolated, maybe if you created a jsfiddle?

How to .load() just a specific div from a page into a a target div, not the whole page

I have the following script that loads a page into a div and not just the targeted div. This is most evident when going back to my index and my header and footer are jammed into the <div id="contentspace"></div>.
I read on here somewhere that the div needs to be placed in it's own page prior to being displayed. Not sure which method would do that. Is this possible without hashtags Thanks for your help
<script type="text/javascript">
$(function() {
$('#header a').click(function() {
$('#contentspace').empty();
$("#contentspace").load(this.href, function(response){
console.log($('#content', response).html())
event.preventDefault();
});
});
});
</script>
The method .load() can load page fragment, simply by specifying a valid jquery selector next to the url.
$('myelement').load('page.html #content', function() {
...
});
Note that when loading page fragments, jquery will remove any SCRIPT element it might contain.
In you example, you would do:
$("#contentspace").load(this.href + ' #content', function(response){
...
});
Did you read the documentation at all? Take a look at the section titled Loading page fragments in the jQuery API for .load(). Essentially you just pass a selector along with the URL of the page to load as the first argument of the method.

Categories

Resources