display an ajax loader icon when submitting a form - javascript

My need is very simple. When a user try to log in and submit the login form, i would to display an ajax loader icon (like ones generated at www.ajaxload.info) in foreground with the background transparent and unclickable (like in this site). when the server has finished, it can display the next page or redisplay the old one with the errors.
How can i do that?
Thank you very much in advance.

Using jQuery (which is a great javascript library and has hundreds of uses besides this one)
you can detect the submit event on the form and take some action, like this:
$(function(){
$('#yourFormId').on('submit', function(e){
//stop the form refreshing the page
e.preventDefault();
//serialize the form for submission to the server
var data = $(this).serialize();
//get the url for the form
var url = $(this).attr('action');
//make an ajax request to submit the form, showing the loader and unclickable div
$('#yourAjaxLoader,#unclickableDiv').fadeIn();
$.post(url, data, function(response){
//the request has completed, so fade out the loader and div
$('#yourAjaxLoader,#unclickableDiv').fadeOut();
});
});
});
To acheive the unclickable div, try some css like this:
/*css*/
#unclickableDiv
{
z-index:99999;
width: 100%;
height: 100%;
opacity: 0.5;
background-color: black;
display:none;
}
and put the div just inside the body tag. when it is faded in, it will be 'above' the rest of the page, making it unclickable. just put your ajax loading icon inside this div so it will show up, too.
You can get jQuery from http://jquery.com and I highly recommend using it anyway, even if not for this. Hope this helps
Update:
The new jQuery on() method has effectively replaced .submit and .click etc since version 1.7, so I've updated this example to reflect that. More info here: http://api.jquery.com/on/

You could use JQuery and take a look at Throbber plugin (http://plugins.jquery.com/plugin-tags/throbber):
Provides trivially easy way to notify users that a request is being loaded and processed in the background, so that they know their action was received and the page has not frozen. Just toggle the message (or image or any element) on or off with $.loading() or $('#foo').loading(). The plugin handles creation and positioning and "pulsing" of the message for you. It also provides a 'mask' option to block the UI (at the call level) while the loading message (or image or any element) is running.

Related

jquery toggleClass not working on img element

I have two buttons ("Approve","Unapprove") and an image of a loading spinner. By default the Approve button is showing and the Unapprove button and loading spinner image are hidden.
When the "Approve" button is clicked I want it to disappear, show the loading spinner, and then perform an ajax request. On completion of the request, I want the loading spinner image to get hidden again. If the ajax request was successful, I want the "Unapprove" button to show. If the ajax request failed, I want the "Approve" button to show again.
The problem I have is that upon completion of the ajax request, my .always() method runs but the spinner image does not get hidden. Here is an example:
https://jsfiddle.net/ebme6fjs/7/
If I change the url of my ajax request to give me a 404 not found error, this process works like it's supposed to:
https://jsfiddle.net/ebme6fjs/8/
Does anyone know why in my first case the spinner.toggleClass("hide"); command isn't running in the always() function? Thanks.
UPDATE:
One interesting thing I found is that if I redefine my spinner variable in the .always() function, it works correctly on a succesful ajax request:
https://jsfiddle.net/ebme6fjs/9/
If you modify the ajax url to receive a 404 though, the same problem of the spinner not disappearing happens again.
In a context where you always want to add the class, use addClass, not toggleClass. In your code, the class is toggled twice: Once in "always" and then again in "fail". So it ends up in the same state as before.
The reason you are targeting the image twice, is because you are defining otherButton like this:
var otherButton = currentButton.siblings();
When what you want to do is this:
var otherButton = currentButton.siblings('button');
toggleClass is most useful when you might want to add or remove the class depending on some condition.
In your code, you were toggling hide class on image twice, in always() callback and done()/fail() ones.
This is because you were targeting image in both variables, spinner & otherbutton.
You should define otherbutton as following:
var otherButton = currentButton.siblings("button");
Not including image in matched set.
As a side note, for code readability, you should use addClass()/removeClass() instead as noted in KWeiss answer and btw, set all your logic for displaying/undisplaying elements only in always() callback.

Browser State - Javascript/JQuery

I am trying to find a way to detect when my browser is loading and show a loading icon.
Also, is this the correct way to go about it or is there a 'standard' practice to accomplish something like that?
Edit: This functionality will be used for one of my sites during database transactions / table building.
I like the JQuery loadmask plugin for this. Apply a mask over the element that is waiting to load some stuff (say via AJAX) on page load:
$('#containerid').mask("<img src='loadinganim.gif'/> Waiting...");
Then when everything is loaded and the user can interact with the element, remove the mask overlay (typically in a callback for an AJAX call after successful completion):
$('#containerid').unmask();
I took a slightly different approach to this problem and this is what I came up with.
Code to reset my loading icon when the page is ready
$(document ).ready(function() {
$('#test').hide();
});
The function that shows the loading icon
$('.loadState').click(function () {
$('#test').show();
});
HTML Code
<div id="test">
<h3> <i class='icon-spinner icon-spin icon-large'></i> Compiling Requested Data </h3>
</div>
And I'm calling the show function my adding this class='loadState' on my submit button.
Edit: Cleaned the mixing between js and jQuery code.
Try an onPage load event listener. Im kind of new to js so I may be off a little.

Loading a part of a page with ajax

I want a part of another page with Ajax Loading. When you click on a button. I have a page. But, i want load only the .section div in the page. When i click on the button. Than only the .section page in the other page must be load.
But, how can i load with ajax / jquery. Only a div from a other page.
You can do this without ajax using jQuery's load method. With this, you can load the content returned into your #div_id or body. Here is an example to load your content into your page's body;
$("#your_button_id").click(function() {
var myUrl = "yourpage.html #div_id_having_data";
$("body").load(myUrl);
return false;
});
Take a look at the jQuery Ajax/load documentation
If i have understood your question properly, then this would be the solution,
On button click load the whole page (.section should be hidden). Then on click of the other button just toggle the .section div.

Multiple Ajax loading indicators on 1 page

I have a page with 2 separate forms that can be submitted via Ajax (jQuery). For each of these forms I'd like to show a loading indicator to the user. I have found a nice piece of code that can easily show these icons, but it only works when there's 1 form.
$('.ajaxloader').hide().ajaxStart(function () {
$(this).show();
}).ajaxStop(function () {
$(this).hide();
});
ajaxloader is a class which shows the loading image as a CSS background image. To use it, I just need to add something like: <span class="ajaxLoader">Busy ...</span>
When I test this with my page (that has 2 forms), and I submit one of the two, then both loading indicators appear (which is quite obvious). Now my question is, how can I show the indicator that needs to be shown? I was thinking about giving the span-tag an id attribute, but then I don't know how to proceed. I want this to be as generic as possible, so I don't have to hardcode and duplicate code a lot.
Thanks!
You could attach the "show loading indicator" callbacks to the Ajax queries themselves, not do a 'catch-all' like your current solution.
Something like this in your $.ajax() call:
$.ajax("/form1/target", {
beforeSend: function() {
$(".ajax-loader-1").show();
},
complete: function() {
$(".ajax-loader-1").hide();
}
});
(And a similar one for your second form, wherever the Ajax call for that is defined)
Have you thought about starting it when your form is submitted and hiding the other.
$('.yourSubmitButton').click(function () {
$(this).parent().find('.ajaxLoader').show();
});
$('.ajaxloader').hide().ajaxStop(function () {
$(this).hide();
});
So the loader will show inside the form that has just been submitted (I assume you are doing a submit with a button or a link?) then both are hidden again when the ajax request stops.

javascript: how to show spinner until file downloads

I have a button to download an excel file. When the user clicks the button, the onClick function calls
window.location= url
and when the downloading is done, the save as dialog popups with the file.
Now, I want to show a spinner until the file dialog appears. How do I do this?
I tried to create a spinner before "window.location" and hide it after that, but the spinner goes away immediately because window.location does not block until the file downloads.
Any ideas?
Thanks.
This would be a solution which only works for Firefox browsers:
<script type="text/javascript">
//<![CDATA[
function download(url){
document.getElementById('spinner').style.display='';
frame = document.createElement("iframe");
frame.onload=function(){document.getElementById('spinner').style.display='none';}
frame.src=url;
document.body.appendChild(frame);
}
//]]>
</script>
In your HTML, have a spinner set up and ready to go:
<div id="spinner" style="background:url('/images/ico-loading.gif') #000 center no-repeat;opacity:.5;width:100%;height:100%;display:none;position:absolute" />
Then call it using this:
<button type="button" onclick="download('/spreadsheet.xls');">DOWNLOAD SPREADSHEET</button>
The button will call our javascript function with the URL we want to download. At this time we make the hidden spinner DIV visible and allow it take over the screen (note position absolute in style). An IFRAME is created to suck down the file. After the file downloads, it is given to the user and the .ONLOAD event is fired which hides the spinner DIV. All done with client side javascript!
You can't do that using just client script, because there is no event for when the download completes.
You would have to download the file through a proxy page on the server, with a unique identity in the URL so that each download could be identified. Then you could send AJAX requests from the script to the server to determine the status of the download.
This code works for jQuery, but with simple modification also for javascript. With this you won't need to change your requests-codes at all.
Create a div element which contains the animation (either another div element with css-animation or an animated gif in an img element) and give it the id = "loadingicondiv". For example like this
&ltdiv id="loadingicondiv">
&ltdiv id="loadingicon" style="background:url('imgs/logo.png') center no-repeat;opacity:1.0;display:none;position:absolute;z-index: 9999;">&lt/div>&lt/div>
Set the style of that div in your css file as follows
#loadingicondiv{
width: 100vw;
height: 100vh;
background: rgba(0,0,0, 0.3);
position: fixed;
z-index: 9999;
}
In the embeded js file enter this
function showAnimation(){
$('#loadingicondiv').css({display : ''});
};
function hideAnimation(){
$('#loadingicondiv').css({display : 'none'});
};
$(document).ajaxStart(showAnimation).ajaxStop(hideAnimation);
This last line makes, that every request sent by your web application, executes the function "showAnimation" at the beginning and executes the function "hideAnimation", when the request is done.
If you don't use jQuery and need pure javascript, simply replace $('#loadingicondiv') with the following code
document.getElementById('loadingicondiv').style.display = 'none'
Note: In case you have some frequent updating on your website, which you don't want to show that animation for, just make the displaying of the animation dependent from a global variable, which you set to false before sending those special requests, which you don't want the animation to be shown for. And don't forget to set it to true, when the request is done by them.

Categories