How to use ajaxStart to show loading spinner? - ajax

I have a webpage that runs a python script with the command shell_exec. I'd like for a loading spinner, the 'Please wait while this page loads' sort of message, to show while the python script is running, then after it is done for the rest of the echo'd HTML to show.
I found what seems like a good solution at https://stackoverflow.com/a/68503/4630491
but I am so new to ajax that I don't know how to use the solution. I tried doing
<div id="loadingDiv">Please wait while this page loads.</div>
<script>var $loading = $('#loadingDiv').hide();
$(document)
.ajaxStart(function () {
$loading.show();
})
.ajaxStop(function () {
$loading.hide();
});
</script>
but this did not work. Do I need to call ajax to execute the ajaxStart? How would I call it? Should I wrap the shell_exec in ajax code?
Thanks a bunch.

Whenever an Ajax request is about to be sent, jQuery checks whether there are any other outstanding Ajax requests. If none are in progress, jQuery triggers the ajaxStart event.
Have a loading gif image like shown below
<div id="loading">
<img src="loading.gif" />
</div>
First hide this loading div(because loading image have to be shown when ajax request is about to sent).
<script>
var $loading = $('#loading').hide();
//Attach the event handler to any element
$(document)
.ajaxStart(function () {
//ajax request went so show the loading image
$loading.show();
})
.ajaxStop(function () {
//got response so hide the loading image
$loading.hide();
});
</script>
For more see at jQuery documentation
Do I need to call ajax to execute the ajaxStart? How would I call it?
Yes when you triggered a ajax request then only ajaxStart will get triggered automatically.
For ajax there are multiple ways with jquery, below I am giving with load function.
$( ".result" ).load( "some_file.py" );
some_file.py output will inserted into div with class name result.
To trigger the load event you can use button click or any other as need.
$( ".trigger" ).click(function() {
$( ".result" ).load( "some_file.py" );
});

Related

Global AJAX event listeners in Can.JS?

Is it possible to bind listeners to when an AJAX request is started in Can.JS? I want to integrate a little loading indicator in my Can.JS project so that users can see when data is being loaded from my server. Using the jQuery $.ajaxStart and $.ajaxSend events didn't work, however the $.ajaxComplete event did fire correctly.
In your example you are binding to the event on document.ready which is after you start the Ajax request. The complete log only shows because the document is ready and binds the event before the Ajax request returns. If you do everything in the correct order on document.ready like this:
$(document).ready(function(e){
$(document).ajaxStart(function(){
console.log('start');
}).ajaxComplete(function(){
console.log("Complete");
});
var TestModel = can.Model({
findAll: "GET http://jsfiddle.net/echo/json/"
});
TestModel.findAll({}, function(result){
alert(result);
});
});
It works as expected (see updated fiddle).

Jquery code not executing on elements that didn't exist on page load

I have a web application that loads javascript on page load:
$(function() {
$('.modal-delete').click(function() {
alert();
});
});
I have a html page with a series of buttons which alert a blank message box when they're clicked:
<button class="modal-delete btn danger"></button>
which works fine.
However, a have some AJAX calls that generate more buttons just like the ones above but NOT on page load! They can be created at any time. These buttons do not do anything but they're meant to load the alerts. They're identical but because they never existed on page load, the Jquery code doesn't work on these buttons. How do I attach the same code to these buttons too?
Many thanks :).
I think you'll want jQuery's 'live()' function:
$('.modal-delete').live('click', function() {
alert();
});
This binds to the elements which match but also rebinds when new elements are added in the future:
"Attach an event handler for all elements which match the current selector, now and in the future"
Change the ready code to this...
$(function() {
$("document").on("click", ".modal-delete", function() {
alert("click");
});
});

Why are the jQuery functions only working the first time they're called?

There is a link that, when clicked, toggles between loading HTML into a div and emptying the div. When the div is clicked to load the html, I use the jQuery ajax load() function. When the text is loading, I want to display "Please wait...", so I tried using the jQuery ajaxStart() and ajaxStop() methods, but they only seemed to work the first time the load() function was called. So I switched to ajaxSend() and ajaxSuccess, but that also only seems to work the first time the load function is called. What's wrong?
HTML:
<p id="toggleDetail" class="link">Toggle Inspection Detail</p>
<p id="wait"></p>
<div id="inspectionDetail"></div>
jQuery:
$(
function(){
$('#toggleDetail').click(function(){
if($.trim($('#inspectionDetail').text()).length)
{
$('#inspectionDetail').empty();
}
else
{
$('#inspectionDetail').load('srInspectionDetailFiller.cfm');
}
});
}
);
$(
function(){
$('#wait').ajaxSend(function() {
$(this).text('Please wait...');
});
}
);
$(
function(){
$('#wait').ajaxSuccess(function() {
$(this).text('');
});
}
);
You should put up the 'Please wait...' message in your click function, then clear the message upon successful completion of your load:
$('#toggleDetail').click(function(){
if($.trim($('#inspectionDetail').text()).length)
{
$('#inspectionDetail').empty();
}
else
{
$('#wait').text('Please wait...');
$('#inspectionDetail').load('srInspectionDetailFiller.cfm', function() {
$('#wait').text('');
});
}
});
Edit: Although ajaxSend should technically work here, I don't recommend it. With ajaxSend, "All ajaxSend handlers are invoked, regardless of what Ajax request is to be sent". It seem overkill to me to hook all Ajax requests on the page which you're really only trying to deal with this single click.

Ajaxed div hide and show hides only after div load

I have this issue. I'm working on a jquery ajaxed site. I have the main content div in the middle and on top the navigation. I need to AJAX the content, because I have flash backgound so that the flash video won't start from beginning after every page load. The only way I was able to do this was with this sort of code:
$(document).ready(function(){
$.ajaxSetup ({
cache: false
});
//For loading
var ajax_load = "<img src='img/load.gif' alt='loading...' /><p>";
// Var
var loadPage1 = "page1.html";
// Load page
$("#page1").click(function(){
$("#content").hide(2000);
$("#content").html(ajax_load).load(loadPage1);
$("#content").show(2000);
});
All other ways to get the div didn't work because there was issues on getting plugins etc. working in the ajaxed div (content).
So... everythig is working fine - but, the div loads it's content from page1.html and shows it and only after this does it hide it and show it. So it loads the page and then does the effects I want to.
Do I need to queue this some how or what's the proper jquery way? I tried delay, stop etc.. but can't seem to solve this out. It's propably very simple.
Thanks.
Show the element in the load callback handler.
i.e:
$("#page1").click(function(){
$("#content").hide();
$("#content").html(ajax_load).load(loadPage1, function(){
$("#content").show(2000)
});
});
.load() takes 2 arguments, the URI and a callback to fire after load.
API is found here: http://api.jquery.com/load/
function() {
$("#content").hide(2000);
$("#content").html(ajax_load).load(loadPage1, function() {
$("#content").show(2000);
});
}

jQuery: Wait for entire page--including ajax--to load?

I'm using some jQuery tabs that load their content via ajax. I'm using $(document).ready() in conjunction with the following code:
// Hide loading animation, show content container
$("#content").show();
$("#loading").hide();
The purpose is to wait until the page is fully loaded, then show the content and hide the loading animation.
However, $(document).ready() only waits for the main page to load, not the external ajax content.
Is there something I can do wait until the ajax is loaded too?
Thanks in advance.
Depending on your ajax library, there is usually an option for supplying a callback which is called when the underlying ajax (get post..) operation is complete. You could use that callback to do your initialization rather than within .ready()....
First, if you wish to show animation while you're loading, use ajaxStart and ajaxStop. It does it auto-painlessly. Here's an example:
// Note! This uses jquery-ui to do the dialog...
jQuery(document).ready(function() {
var body = jQuery("body");
body.append('<div id="ajaxBusy"><div style="text-align:center" ><p>Communicating with server...<br \/>Please wait for this operation to finish.<br \/><img src="\/js\/jquery.smallhbar.indicator.gif" \/><\/p><\/div><\/div>');
jQuery('#ajaxBusy').css({
display:"none",
margin:"0px",
width:"260px",
height:"170px",
padding:"5px",
textAlign:'center'
});
jQuery("#ajaxBusy").dialog({
autoOpen: false,
bgiframe: true,
closeOnEscape: false,
//modal: true,
title: 'Shipping Department'});
jQuery(document).ajaxStart(function() {
jQuery('#ajaxBusy').dialog('open');
});
jQuery(document).ajaxStop(function() {
jQuery('#ajaxBusy').dialog('close');
});
});
With this code in my jQuery.ready section, a pretty dialog automatically flashes when ajax operations are occurring.
Finally, if you need to show content afterwards, you need to put your show() method within the success function of your ajax call. If you have multiple ajax calls happening, you'll need to use some variables as flags to signal when everything is done (clunky).
Do you have one or more than one ajax call happening?

Resources