I have a function that displays contents of a posts when clicked on. I want the loading spinner to display and delay for few sections before the post content appears. The issue here is when I click on each post, the spinner appears for maybe 1ms and in some cases it disappears long before the content appears.
function showPost(id) {
setTimeout(function() {$('#loader').show();},1);
$('#pcontent').empty();
$.getJSON('http://howtodeployit.com/category/daily-devotion/?json=get_post&post_id=' + id + '&callback=?', function(data) {
var $postcon = $('<div/>').append([$("<h3>", {html: data.post.title}),$("<p>", {html: data.post.content})]);
$postcon.appendTo('#pcontent');
});
}
Spinner HTML:
<div id='loader'><img src="css/images/loader.gif"/></div>
Try this:
function showPost(id) {
$('#loader').show();
$('#pcontent').empty();
$.ajax({
url: 'http://howtodeployit.com/category/daily-devotion/?json=get_post&post_id=' + id + '&callback=?',
dataType: 'json',
success: function (data) {
var $postcon = $('<div/>').append([$("<h3>", {
html: data.post.title
}), $("<p>", {
html: data.post.content
})]);
$postcon.appendTo('#pcontent');
$('#loader').hide();
}
});
}
gif image always behave differently on every device..basically it depends upon device's processing speed. so better option is to use image sprites and animate it with javascript..
In your case at page load there is nothing processing..but as page starts to load device's processor cant handle the load and as a result your gif image gets slower
It seems from your last commented line that you are using a timeout to hide the loader. Instead You should handle the hiding inside the callback function of your ajax request, so that loader hides after request is completed, not after a fixed amount of time:
function showPost(id) {
$('#loader').show();
$('#pcontent').empty();
$.getJSON('http://howtodeployit.com/category/daily-devotion/?json=get_post&post_id=' + id + '&callback=?', function(data) {
$('#loader').hide();
var $postcon = $('<div/>').append([$("<h3>", {html: data.post.title}),$("<p>", {html: data.post.content})]);
$postcon.appendTo('#pcontent');
});
}
Related
I'm building a simple practice project where each page is loaded via AJAX and would present a fadeIn, fadeOut transition using CSS animation opacity.
The problem is that the addClass and removeClass are not being executed.
JS (JQuery)
$(document).ready(function() {
// $('.mainSplash').css('height',$(window).height() - 60);
$(".aboutBtn").click(function(e) {
e.preventDefault();
var pageTitle = $(this).text();
var pageUrl = $(this).attr('href');
changePage(pageUrl, true, pageTitle);
}); // click
function changePage(url, bool, pageTitle){
$('#wrapper').addClass('animate');
loadContent(url, bool, pageTitle);
}
function loadContent(url, bool, pageTitle){
$.ajax({
url: './' + url,
type: 'get',
contentType: 'html',
success: function(data){
// load content
$('#content').html(data);
// Change url
if(url != window.location){
window.history.pushState({path: url}, pageTitle, url);
}
},
complete: function(){
$('#wrapper').removeClass('animate');
}
});
}
});
Here's the full Codepen project example
If you are having issues with the animation being removed before it finishes and thus it is not visible. You would want to listen for when the animation event ends, and remove the class in the callback there (if it really needs to be removed) instead of removing it when the page is done loading.
I am using jquery mobile auto complete , Please see the demo at http://jsfiddle.net/Q8dBH/11/.
So whenever user press any letter,i need to show some message like "please wait."
So i added some code like below.But its showing only 1st time or 2nd time or not showing at all some times..How to show message whenever user types something until server responds back with data.
$ul.html('<center>Searching Please Wait<br><img src="http://freegifts.in/diet/themes/images/ajax-loader.gif"></center>');
my full js is below.
$(document).on("pagecreate", ".ui-responsive-panel", function () {
$(document).on("click", "li", function () {
var text = $(this).text();
$(this).closest("ul").prev("form").find("input").val(text); });
$("#autocomplete").on("filterablebeforefilter", function (e, data) {
var $ul = $(this),
$input = $(data.input),
value = $input.val(),
html = "";
$ul.html("");
if (value && value.length >0) {
$ul.html('<center>Searching Please Wait<br><img src="http://freegifts.in/diet/themes/images/ajax-loader.gif"></center>');
//$ul.listview("refresh");
$('.ui-responsive-panel').enhanceWithin();
$.ajax({
url: "http://freegifts.in/diet/calorie.php",
dataType: "jsonp",
crossDomain: true,
data: {
q: $input.val()
}
})
.then(function (response) {
$.each(response, function (i, val) {
html += "<li data-role='collapsible' data-iconpos='right' data-shadow='false' data-corners='false'><h2>Birds</h2>" + val + "</li>";
});
$ul.html(html);
//$ul.listview("refresh");
//$ul.trigger("updatelayout");
$('.ui-responsive-panel').enhanceWithin();
});
}
});
});
Working example: http://jsfiddle.net/Gajotres/Q8dBH/12/
Now this is a complex question. If you want to show jQuery Mobile AJAX loader there's one prerequisite, AJAX call must take longer then 50 ms (jQuery Mobile dynamic content enhancement process time will not get into account). It works in jsFiddle example but it may not work in some faster environment.
You can use this code:
$.ajax({
url: "http://freegifts.in/diet/calorie.php",
dataType: "jsonp",
crossDomain: true,
beforeSend: function() {
// This callback function will trigger before data is sent
setTimeout(function(){
$.mobile.loading('show'); // This will show ajax spinner
}, 1);
},
complete: function() {
// This callback function will trigger on data sent/received complete
setTimeout(function(){
$.mobile.loading('hide'); // This will hide ajax spinner
}, 1);
$.mobile.loading('hide'); // This will hide ajax spinner
},
data: {
q: $input.val()
}
})
beforeSend callback will trigger AJAX loader and complete callback will hide it. Of course this will work only if AJAX call lasts more then 50ms. Plus setTimeout is here because jQuery Mobile AJAX loader don't work correctly when used with web-kit browsers, it is a triggering workaround.
I'm using a form and Ajax to pull an image dynamically to replace another image in the .results div. My first try worked, but the page jumped up when the image was removed and jumped back down when the image was loaded. I figured I could add style attribute to give the div a height, then after the image is loaded remove the style attribute. What I have below works 70% of the time, the other 30% the stye attribute is being removed before the image is loaded and the page jump is still there. Is there a way to remove the style attribute only after the image is completely loaded? Or set a delay or something? I'm a JS and Ajax noob, so please be gentle.
(function($){
$(function(){
var $form = $('#customize'), // Search form
$target = $('.results'), // Results container
rp = 'product_search/results_only_ajax'; // Template for results only
// Function to execute on success
var success = function(data, status, xhr) {
$target.html(data);
$('.loading').html('<p></p>');
// Remove style
$('.results').removeAttr("style");
};
// Hijack the form on submit
$form.submit(function(){
// Tell target we're loading
$('.loading').html('<p>Loading...</p>');
// get height of container, and set height
currentHeight = $('.results').outerHeight();
$('.results').css("height", currentHeight);
// Add custom result page to data
var data = $form.serialize()
+ '&result_page=' + rp;
// Perform the ajax call
$.ajax({
type: 'POST',
url: $form.attr('action'),
data: data,
success: success,
dataType: 'html'
});
// Don't submit the form afterwards
return false;
});
});
})(jQuery);
EDIT:
// Function to execute on success
var success = function(data, status, xhr) {
$target.html(data);
$('.loading').html('<p></p>');
// $('.results').removeAttr("style");
setTimeout(function () {
$('.results').removeAttr("style");
}, 1000);
};
I added a Timeout which is working ok for now.
I'm Using Web service using AJAX Call In My HTML Page . Web Service Returning Data Nearly 30 to 40 second's .
During This Loading Time I Need to Use Some Loading Gif Images After Data Completely Received Form Web Service The Loading Image Must Be Hide.
I'm Using Only HTML,JAVASCRIPT,CSS,J Query.
Any Idea Or Samples Needed.
I'm Using Following Code
$(document).ready(function () {
document.write('<img src="http://www.esta.org.uk/spinner.gif">');
});
$( window ).load(function() {
//This following Function Related To My Design
jQuery(".chosen").data("placeholder", "Select Frameworks...").chosen();
var config = {
'.chosen-select': {},
'.chosen-select-deselect': { allow_single_deselect: true },
'.chosen-select-no-single': { disable_search_threshold: 10 },
'.chosen-select-no-results': { no_results_text: 'Oops, nothing found!' },
'.chosen-select-width': { width: "95%" }
}
for (var selector in config) {
$(selector).chosen(config[selector]);
}
});
In The Above Code My Problem Is On Page Load Gif Image Show But It's Not Hide Only Gif Image Only Showing.
Put a hidden image on your page and as soon as your ajax call is made, make that image visible
$('#image').show();
$.ajax({
complete: function(){
$('#image').hide();
}
});
and hide that image again on Complete of Ajax call.
Use your ajax request callback (on success/failure) instead of page load.
When sending the request just show a gif animation by setting the Display to block
then when you have the data set the display to none
or use jquery
function showHourGlass()
{
$("#gifimage").show();
}
function hideHourGlass()
{
$("#gifimage").hide();
}
You ask for ideas, I have one sample -
http://www.myntra.com/shoes
load scroll down fastly this is the ajax jquery request which is exact output which you have mentioned in your question
Check source code
Jquery Ajax loading image while getting the data
This what the html looks like:
<button id="save">Load User</button>
<div id="loading"></div>
and the javascript:
$('#save').click(function () {
// add loading image to div
$('#loading').html('<img src="http://preloaders.net/preloaders/287/Filling%20broken%20ring.gif"> loading...');
// run ajax request
$.ajax({
type: "GET",
dataType: "json",
url: "https://api.github.com/users/jveldboom",
success: function (d) {
// replace div's content with returned data
// $('#loading').html('<img src="'+d.avatar_url+'"><br>'+d.login);
// setTimeout added to show loading
setTimeout(function () {
$('#loading').html('<img src="' + d.avatar_url + '"><br>' + d.login);
}, 2000);
}
});
});
I hope this will help you.
so i have a function that is triggered a click of a button (imagine a published/unpublished button)
so as soon as the function loads i change the element to be a loader gif
function updateStatus(event, status, element, data, action) {
//init loader
$("#" + element).find("img").attr("src", "../../img/images/loader.gif");
that works fine
then I do an ajax request where i pass the data (so i can update the database via the rest)
var request= $.ajax({
type: 'get',
url: "../testResponses/status.php",
data:data
});
again that is all good and then when the request is done I can change the image
request.done(function(msg) {
$("#" + element).find("img").attr("src", "../../img/images/status/"+newStatus+".png");
$("#" + element).attr("data-user-status", newStatus);
});
seeing as this is still a proof of concept I want to add a 2 second delay before the loader image disappears and the new status us shown
I tried
request.delay(2000).done ...
which returned an error and
$("#" + element).delay(2000).find("img").attr("src", "../../img/images/status/"+newStatus+".png");
which just didnt make any difference..
can anyone help?
You can use setTimeout() to trigger the logic in 2 seconds after you get the request:
request.done(function(msg) {
setTimeout(function(){
// change the image
}, 2000);
});
Another solution is to use the .delay() queue
$("#" + element).delay(2000).delay(function (next) {
$(this).find("img").attr("src", "../../img/images/status/" + newStatus + ".png");
next();
});