loading image during delay - javascript

I got the delay to work when you click on the buttons but I cant get the loading gif to display during the delay.
Thanks
function () {
$('.sectionThreeTab:not(.tabActive)').click(function () {
$('ajax-loader.gif').bind('ajaxStart', function () {
$(this).show();
}).bind('ajaxStop', function () {
$(this).hide();
});
$('.tabActive').removeClass('.tabActive');
$(this).addClass('tabActive');
var lesson = $(this).attr('lesson');
var self = $(this);
setTimeout(function () {
$.ajax({
type: "GET",
url: 'lessons/' + lesson + '.htm',
datatype: "json",
success: function (data) {
$('#sectionTabContent').append(data);
}
})
}, 3000);
return false;
});
}

You can try this instead of what you have:
Delete this part:
$('ajax-loader.gif').bind('ajaxStart', function () {
$(this).show();
}).bind('ajaxStop', function () {
$(this).hide();
});
And change the setTimeout to this:
setTimeout(function () {
$("#loading").show();
$.ajax({
type: "GET",
url: 'lessons/' + lesson + '.htm',
datatype: "json",
success: function (data) {
$('#sectionTabContent').append(data);
},
complete: function() {
$("#loading").hide();
}
})
}, 3000);
Please also post your html so we can see if everything else is in order.
Edit:
<div id="loading" class="grayBackground withBorder10" style="display:none">
<img alt="Loading..." src="img/ajax-loader.gif" />
</div>

I believe your targeting the loading image incorrectly, try:
$('#ajaxLoader').bind('ajaxStart', function () {
$(this).show();
}).bind('ajaxStop', function () {
$(this).hide();
});
Where your loading image has an Id #ajaxLoader (replace to suit your HTML).

Related

Preload that waits for a function to execute

I'm working on a preload for an article abstracts page. I manage to get the preload to show, but the first time the page loads, the preload disappears before the article summaries are fully loaded. It takes about 5 seconds for summaries to load after the preload disappears. Behavior that is not wanted.
The second time onwards it works as desired
$(window).on("load", function () {
var p2 = new Promise(function (resolve, reject) {
resolve(1);
});
p2.then(function (value) {
$('#preloader .inner').fadeOut();
return value + 1;
}).then(function (value) {
PegaListaPosts();
return value + 1;
}).then(function (value) {
$('#preloader').delay(10).fadeOut('slow');
return value + 1;
}).then(function (value) {
$('body').delay(10).css({ 'overflow': 'visible' });
});
//$('#preloader .inner').fadeOut();
//var con = await PegaListaPosts();
//$('#preloader').delay(10).fadeOut('slow');
//$('body').delay(10).css({ 'overflow': 'visible' });
});
function PegaListaPosts() {
$.ajax({
url: "/Blog/PegaResumoPost",
type: "GET",
datatype: "json",
contenttype: "application/json; charset=utf-8",
success: function (data) {
var lista = data.resumosPosts;
if (data.culturaAtual == 2) {
CarregarResumos(lista, data.culturaAtual);
}
else if (data.culturaAtual == 1) {
CarregarResumos(lista, data.culturaAtual);
}
else {
CarregarResumos(lista, data.culturaAtual);
}
},
});
}
I solved the problem as follows.
I put the "PegaListaPosts()" function in Window onload, and inside the called function, I call the preload functions.
The code was like this:
$(window).on("load", function () {
PegaListaPosts();
});
function PegaListaPosts() {
$('#preloader .inner').fadeOut();
$.ajax({
url: "/Blog/PegaResumoPost",
type: "GET",
datatype: "json",
contenttype: "application/json; charset=utf-8",
success: function (data)
{
var lista = data.resumosPosts;
if (data.culturaAtual == 2) {
CarregarResumos(lista, data.culturaAtual);
}
else if (data.culturaAtual == 1) {
CarregarResumos(lista, data.culturaAtual);
}
else {
CarregarResumos(lista, data.culturaAtual);
}
$('#preloader').delay(10).fadeOut('slow');
$('body').delay(10).css({ 'overflow': 'visible' });
},
error: function () {
$('#preloader').delay(10).fadeOut('slow');
$('body').delay(10).css({ 'overflow': 'visible' });
alert('Não foi possível carregar os resumos dos posts!');
}
});
}
With this, the preload only disappears when the article summaries have all been loaded.

How to repeat ajax request depending return

I have this code :
.on('finish.countdown', function() {
var onEndAuction = function () {
$.ajax({
type: "POST",
url: "{{path('app_auction_end')}}",
data: {auctionId:{{ aReturn.oAuction.getId()}}},
success: function (data) {
console.log(data);
if (data == 0) {
setTimeout(onEndAuction, i_timer);
} else {
document.location.reload(true);
}
}
});
};
});
I want if data == 0 need to make another call on app_auction_end after 10 sec. Can you help me please ? Thx in advance and sorry for my english
Give the operation a named function:
var someFunction = function () {
$.ajax({
//...
});
};
Which you would then use for your .on() call:
.on('finish.countdown', someFunction)
And in the success handler, set a timeout for that function:
if (data == 0) {
setTimeout(someFunction, i_timer);
}
.on('finish.countdown', function() {
var onEndAuction = function () {
$.ajax({
type: "POST",
url: "{{path('app_auction_end')}}",
data: {auctionId:{{ aReturn.oAuction.getId()}}},
success: function (data) {
console.log(data);
if (data == 0) {
setTimeout(onEndAuction, i_timer);
} else {
document.location.reload(true);
}
}
});
};
//do our initial call otherwise it will never get called.
onEndAuction();
});

Show Gif on click and Hide after Ajax Success

I found lots os posts with the solution to my problem, but no one works to me...
I tried like:
<div class="ibox-content">
<div id="carregando" class="text-center" style="display:none">
<img src="~/Imagens/logo.png" />
</div>
<div id="container" style="height: 460px; margin: 0 auto"></div>
</div>
My JS is called on a button clink who calls a funcion like bellow:
$("#atualiza").click(function () {
$(document).ajaxStart(function () {
$("#carregando").show();
});
$.ajax({
url: '/Portaria/AtendOperador',
dataType: "json",
type: "GET",
data: { 'data1': data1, 'data2': data2, 'evento': evento, 'cuc': cuc, 'conta': conta },
async: false,
cache: false,
delay: 15,
success: function (data) {
var Categories = new Array();
var Series = new Array();
for (var i in data) {
Categories.push(data[i].Operador);
Series.push(data[i].Fechados);
}
var CategArray = JSON.parse(JSON.stringify(Categories));
atendOperador(CategArray, Series);
$(document).ajaxStop(function () {
$("#carregando").hide();
});
},
error: function (xhr) {
alert('error');
$(document).ajaxStop(function () {
$("#carregando").hide();
});
}
});
});
function atendOperador(CategArray, Series) {
var chart2 = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'bar'
}
});
}
Even I put the code:
$( document ).ajaxStart(function() {
$( "#carregando" ).show();
});
The image appear only after ajax finishing. Using the two blocks, show and Hide, the image not appear, so, i tried to remove the hide block and i could see that the problem is: Show and Hide happens together when ajax is loaded like:
I cliked on button and noting happened like: http://prntscr.com/ars97n
And after few seconds, Ajax load data and show icon and data together: http://prntscr.com/ars9xq
Try $("#carregando").hide(); instead of $(document).ajaxStop(function ()$("#carregando").hide();});
edit: ajaxStart and ajaxEnd are event handlers. I think they should be registered outside of the click function. Something like this:
$(document).ready(function(){
$(document).ajaxStart(function () {
$("#carregando").show();
});
$(document).ajaxStop(function () {
$("#carregando").hide();
});
$("#atualiza").click(function () {
/* all your code here except for the ajaxStart/ajaxStop portion */
});
});
As Karl stated, the best way to do it is without using ajaxStart/ajaxStop event handlers, or even better, without using jQuery at all.
document.querySelector('.get-data').addEventListener('click', function() {
document.querySelector('.display-data').textContent = null;
document.querySelector('.loading').style.display = 'block';
var request = new XMLHttpRequest();
request.open('GET', 'http://jsonplaceholder.typicode.com/photos', true);
request.onload = function() {
if (this.status >= 200 && this.status < 400) {
// Success!
var data = JSON.parse(this.response);
document.querySelector('.loading').style.display = 'none';
document.querySelector('.display-data').textContent = JSON.stringify(data[0]);
} else {
// We reached our target server, but it returned an error
document.querySelector('.loading').style.display = 'none';
}
};
request.onerror = function() {
// There was a connection error of some sort
document.querySelector('.loading').style.display = 'none';
};
request.send();
});
<button class="get-data">Get Data</button>
<div class="loading" style="display: none">
<img src="https://upload.wikimedia.org/wikipedia/commons/2/28/InternetSlowdown_Day.gif" width="50px">
</div>
<div class="display-data"></div>
Finally! I found the problem here! All ways I tried before works now, with this modification I did.
Just:
$("#carregando").show();
Or:
$(document).ajaxStart(function () {
$("#carregando").show();
});
$(document).ajaxStop(function () {
$("#carregando").hide();
});
Or:
beforeSend: function() {
$("#carregando").show();
},
complete: function() {
$("#carregando").hide();
},
All my problem were here: http://prntscr.com/asbxbk!!!
So, I commented that async and works!!!
$("#atualiza").click(function () {
$(document).ajaxStart(function () {
$("#carregando").show();
});
$(document).ajaxStop(function () {
$("#carregando").hide();
});
$.ajax({
url: '/Portaria/AtendOperador',
dataType: "json",
type: "GET",
data: { 'data1': data1, 'data2': data2, 'evento': evento, 'cuc': cuc, 'conta': conta },
//async: false, COMMENTED!!!
success: function (data) {
var Categories = new Array();
var Series = new Array();
for (var i in data) {
Categories.push(data[i].Operador);
Series.push(data[i].Fechados);
}
var CategArray = JSON.parse(JSON.stringify(Categories));
atendOperador(CategArray, Series);
},
error: function (xhr) {
alert('error');
}
});
});
Karl's answer is correct if you want to show the same git for all ajax request on the page
But if you want to do it for this particular AJAX the follow this
$("#atualiza").click(function () {
$.ajax({
beforeSend: function() { $("#carregando").show(); }, //It will show the gif just before sending the request
url: '/Portaria/AtendOperador',
dataType: "json",
type: "GET",
data: { 'data1': data1, 'data2': data2, 'evento': evento, 'cuc': cuc, 'conta': conta },
async: false,
cache: false,
delay: 15,
success: function (data) {
var Categories = new Array();
var Series = new Array();
for (var i in data) {
Categories.push(data[i].Operador);
Series.push(data[i].Fechados);
}
var CategArray = JSON.parse(JSON.stringify(Categories));
atendOperador(CategArray, Series);
$("#carregando").hide(); //this will hide the gif in case of AJAX success
},
error: function (xhr) {
alert('error');
$("#carregando").hide(); //this will hide the gif in case of AJAX failure
}
});
});
Hope this will help you

Jquery $(this).closest('form'); not working after button click

I have the following js code:
$("#add_station").on('click', function () {
$(this).closest('form').submit(function () {
alert("working!");
$.ajax({
url: advoke.base_url + "/new-vendor-user/station/ajax",
method: 'post',
processData: false,
contentType: false,
cache: false,
dataType: 'json',
data: new FormData(this),
beforeSend: function () {
$('.info').hide().find('ul').empty();
$('.success_message').hide().find('ul').empty();
$('.db_error').hide().find('ul').empty();
},
success: function (data) {
if (!data.success) {
$.each(data.error, function (index, val) {
$('.info').find('ul').append('<li>' + val + '</li>');
});
$('.info').slideDown();
setTimeout(function () {
$(".info").hide();
}, 5000);
} else {
$('.success_message').slideDown();
$('#add_station').remove();
$("#station").append(data.new_station);
setTimeout(function () {
$(".success_message").hide();
}, 5000);
} //success
},
error: function () {
//db error
$('.db_error').append('<li>Something went wrong, please try again!</li>');
$('.db_error').slideDown();
//Hide error message after 5 seconds
setTimeout(function () {
$(".db_error").hide();
}, 5000);
} //error
});
});
return false;
});
When I click the button with the id add_station it alerts on click function after $($this).closest('form').submit(function(){...) it doesn't work as you can see I've put an alert 'works' after submit function.I get no errors on the console and I can't figure what the problem is. Also, the button that is clicked is inside a form.
I need to use $($this).closest('form').submit(function(){...) inside because after ajax success a new form will be generated with add station button that will use this code.
You should block the default submit trigger by using
e.preventDefault();
$(this).closest('form').submit(function (e) {
e.preventDefault();
<!--rest of the code-->
})
add a separately submit handler
$("#add_station").on('click', function () {
$(this).closest('form').submit();
});
$("form").on("submit", function (e) {
e.preventDefault();
alert("working!");
$.ajax({
url: advoke.base_url + "/new-vendor-user/station/ajax",
method: 'post',
processData: false,
contentType: false,
cache: false,
dataType: 'json',
data: new FormData(this),
beforeSend: function () {
$('.info').hide().find('ul').empty();
$('.success_message').hide().find('ul').empty();
$('.db_error').hide().find('ul').empty();
},
success: function (data) {
if (!data.success) {
$.each(data.error, function (index, val) {
$('.info').find('ul').append('<li>' + val + '</li>');
});
$('.info').slideDown();
setTimeout(function () {
$(".info").hide();
}, 5000);
} else {
$('.success_message').slideDown();
$('#add_station').remove();
$("#station").append(data.new_station);
setTimeout(function () {
$(".success_message").hide();
}, 5000);
} //success
},
error: function () {
//db error
$('.db_error').append('<li>Something went wrong, please try again!</li>');
$('.db_error').slideDown();
//Hide error message after 5 seconds
setTimeout(function () {
$(".db_error").hide();
}, 5000);
} //error
});
});
after ajax success a new form will be generated with add station
button that will use this code
If you generate a new button you have to bind the click again after it is placed to the dom.

query clearInterval when variable is "x"

I have made a function that is controlling a row in a my database for a certain number with AJAX.
Im calling the function with a click function and putting the function in a setInterval function to make the check 10 times a second.
In the beginning it will return 0, but at some point (usually within 5 seconds) it will return something els than 0, when it does i want to clearInterval.
But im not sure how to this?
This is my function:
function get_buzzer() {
$.ajax({
url: 'ajax_buzzer.php',
dataType: 'json',
async: false,
type: 'post',
data: {
job: 'get'
},
success:function(s) {
if(s['number'] == 0) {
var player = false;
} else {
var player = true;
}
}, error:function(e) {
}
});
}
$(document).ready(function() {
$('#test').click(function() {
var buzzer = setInterval("get_buzzer()",100);
});
});
You can do something like
$(document).ready(function () {
//make buzzer a share variable
var buzzer;
$('#test').click(function () {
buzzer = setInterval(get_buzzer, 100);
});
function get_buzzer() {
$.ajax({
url: 'ajax_buzzer.php',
dataType: 'json',
async: false,
type: 'post',
data: {
job: 'get'
},
success: function (s) {
if (s['number'] != 0) {
//if number is not 0 then clear the interval
clearInterval(buzzer)
}
},
error: function (e) {}
});
}
});
Try this : declare global variable to store interval and call window.clearInterval in success call of ajax
var buzzer;
function get_buzzer() {
$.ajax({
url: 'ajax_buzzer.php',
dataType: 'json',
async: false,
type: 'post',
data: {
job: 'get'
},
success:function(s) {
if(s['number'] == 0) {
var player = false;
} else {
var player = true;
//clear interval
window.clearInterval(buzzer);
}
}, error:function(e) {
}
});
}
$(document).ready(function() {
$('#test').click(function() {
buzzer = setInterval("get_buzzer()",100);
});
});
Use:
inside success use: And make var buzzer Gloval var.
clearInterval(buzzer);
Refence
You just need to clear the interval in the success handler of ajax call over a condition.
success: function (s) {
if (s['number'] != 0) {
//if number is not 0 then clear the interval
clearInterval(buzzer)
}
},
error: function (e) {}

Categories