JQuery AJAX success + fadeIn - javascript

I'm using AJAX to load survey content into a container on a page, and during the transition, I fadeOut the container and fadeIn when it's done. It works fine for pages 1-4, but stops working for page 5. The content loads for page 5, but the container doesn't fadeIn.
success: function(data){
$("div#surveyContainer").fadeOut(function(){
$("div#surveyContainer").html(data).hide().fadeIn();
}); // end fadeout
}
There is no reference to surveyContainer anywhere in page 5. All I can think of is that something is timing out causing the fadeIn to not get triggered. The load time is about 36ms. I set the php script to where it's sending data to report all errors (and the data is making it into the Db just fine), but all I'm getting is the content I expect, but the container stays display:none. If I remove the fades, everything works fine :/
I've also tried this to no avail:
success: function(data){
$("div#surveyContainer").fadeOut(function(){
$("div#surveyContainer").html(data);
$("div#surveyContainer").fadeIn();
}); // end fadeout
}

Try adding a .stop(); see reference here
success: function(data){
$("div#surveyContainer").fadeOut(function(){
$(this).html(data).stop(true, true).fadeIn();
}); // end fadeout
}
This should stop any animations that are currently happening, force them to go straight to their ending point (where they were animating to) and clear the animation queue. You can probably get rid of the hide() this way too.
Also, you can just use this inside the callback for, well, I dont' know why. but you can.

Not sure why it would break on a individual page tho.
Perhaps you could try it in the callback of .hide():
$("div#surveyContainer").html(data).hide('slow', function(){
$(this).fadeIn();
});
As Interstellar_Coder pointed out. You have already hidden the div#surveyContainer when you faded it out. You now just need to load up your data and fade it in.
success: function(data){
$("div#surveyContainer").fadeOut(function(){
$(this).html(data).fadeIn(); // Removed the .hide()
}); // end fadeout
}

Don't link to http://code.jquery.com/jquery-latest.js from a page using encryption (HTTPS). Host the code locally.

Related

Function initiated in ajax call only works one time

I am using a plugin called mixitup that makes sure I have a masonry layout with some animations.
The masonry comes from another page which gets loaded in through ajax. I have a search bar which searches for photos and returns them from the masonry page. The issue is this works the first time but not the second time and so on. Why is that?
My code for the search input:
$('.photosearchinput').keyup(function(e) {
clearTimeout($.data(this, 'timer'));
if (e.keyCode == 13){
searchphotos(true);
}else{
$(this).data('timer', setTimeout(searchphotos, 500));
}
});
My function that makes the ajax call and which has my masonry mixitup function in the complete:
function searchphotos(force) {
var photoform = $(".photosearchform").serialize();
$.ajax({
type:'post',
url:"includes/photoresults.php",
data:({photoform: photoform}),
success:function(data){
$( "#searchphotos" ).show().empty().append( data );
},
complete:function(){
// I tried calling #masongallery from the body (body always stays the same and does not get added again)
$('body').find('#masonrygallery').mixItUp({
selectors: {
target: '.tile',
filter: '.filter',
sort: '.sort-btn'
},
animation: {
animateResizeContainer: false,
effects: 'fade scale'
}
});
}
});
}
I thought maybe the DOM gets reloaded and jquery cannot find the element #masonrygallery anymore so I tried calling it like this: $('body').find('#masonrygallery').mixItUp({ the body never gets reloaded so maybe this would fix it, but no. I get the same result. It works the first time, but not any time after that.
I have made a video to show what I mean: https://streamable.com/njy6x7
I get no errors in my console. And when I look in the network tab to see what ajax is retrieving, I see the correct images, they are just not visible as masonry layout (in fact they are not visible on the page at all but this is because of the plugin).

jQuery not displaying appended content

When I drop a debug point in my source file I can see the following image:
But when I remove this debug point, I only see the following:
The change in color is affected by an overlay with some opacity.
The relevant code is:
flashSuccessMessage = function(msg) {
$('#overlay').hide();
var $ch = $("#content-header");
$ch.after('<div id="flash_message" class="alert"></div>');
var $fm = $("#flash_message");
$fm.addClass("alert-success");
$fm.append(msg);
$fm.show().children().show();
$fm.fadeOut(3000);
$fm.empty();
}
And in this case msg is "Job Type Added Successfully"
I can't understand why I only see the message when I break on the execution after the point where I call $fm.append(msg); It doesn't matter which I break on after that (of the three lines), it will appear. When I don't have any break and let the page execute the script, the green alert appears but no words.
Any ideas?
I've tried various jQuery methods here - instead of .append() using .html() for example, and I've tried inserting the msg inside the with the flash_message id to begin, tried inserting the message wrapped in tags, tried re-ordering things, (but I need to clear the contents of this div at the end...)
I've used jQuery's .delay() method, etc. Is it jumping to executing .empty() despite other elements using a timer to fully execute?
Add a callback to your fadeOut so that the contents aren't emptied until $fm is completely hidden:
flashSuccessMessage = function(msg) {
$('#overlay').hide();
var $ch = $("#content-header");
$ch.after('<div id="flash_message" class="alert"></div>');
var $fm = $("#flash_message");
$fm.addClass("alert-success");
$fm.append(msg);
$fm.show().children().show();
$fm.fadeOut(3000, function(){ // empty() is not called until
$(this).empty(); // the animation is complete
});
}
Without the callback, the empty() method is being triggered immediately after fadeOut(). This causes the content to be emptied BEFORE the animation is complete.
More information on jQuery's fadeOut method can be found in the docs.
The animations in JQuery are asynchronous, so the code keeps executing while the animation happens. .fadeOut has a completion block which you can read about at http://api.jquery.com/fadeOut/.
So, instead of calling fm.empty() after your animation, you should put it inside a function and pass that function into fade out. That function will then run after the animation completes.
but I need to clear the contents of this div at the end...
Use html instead of append:
$fm.html(msg);
$fm.fadeOut(3000, function(){
$fm.empty();
});
Check doc of fadeOut:
.fadeOut( [duration ] [, complete ] )
complete
Type: Function()
A function to call once the animation is complete.

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
});
});
});
});

Why isnt my jquery working when I use external pages

Im using jquery to load in 2 external pages, one called search.php and the other is called info.php. I am displaying them each on a single page called user.php but only when there link has been clicked in the navigation bar. Unfortunately I am currently experiencing a problem, when I use this section of script:
$(document).ready(function() {
$('#content_area').load($('.menu_top:first').attr('href'));
});
$('.menu_top').click(function() {
var href = $(this).attr('href');
$('#content_area').hide().load(href).fadeIn('normal');
return false;
});
My page seems to flicker and stall for 2 seconds before changing the content. I have noticed However if I remove the .hide and fadeIn it seems to work fine. How can I still use the fade-in but eliminate the stall and flickering?
jQuery adds .fadeIn, .hide, and other effects to it's effect's queue. So it's calling .load() instantly JUST AFTER it sends the .hide to the effect's queue/and the .hide isn't completed.
You can do a callback on the .hide method:
$('#content_area').hide(function(){
$('#content_area').load(href).fadeIn('normal');
})
This allows hide to finish first.
try experimenting with .stop to see if it helps with flickering:
$('#content_area').hide().stop(true,true).load(href).stop(true,true).fadeIn('normal');
for flickering use animate instead of fadeIn or fadeOut
for fadeout
$("youeSelector").animate({ opacity: 0 }, 'slow');
for fadein
$("youeSelector").animate({ opacity: 1 }, 'slow');
and as far as the second problem goes make sure you are not including the script files twice

jQuery Horizontal Ticker with Continuous loop

I am using a jQuery ticker which is pretty cool. It works well with predefined content, but I want to build my tags dynamically by getting the data from a feed via the $.ajax method.
http://progadv.uuuq.com/jStockTicker/
The problem is when I do this the ticker wont work, as it looks like the function might be loading before my page content has loaded. Can anbody think of a way around this?
$(function() {
$("#ticker").jStockTicker({interval: 45});
});
$(document).ready(function() {
$("#ticker").jStockTicker({interval: 45});
});
You need to call the jStockTicker function from within the success method with the Ajax call, because like you say, jStockTicker is calculating the dimensions for scrolling before the content has been added to the page.
$.ajax({
url: 'ajax/test.html',
success: function(data) {
//Populate $('#ticker') with data here, e.g...
$('#ticker').html(data);
//Now call jStockTicker
$("#ticker").jStockTicker({interval: 45});
}
});
Something like that ought to do it.
Rich
I have never used the jStockTicker; however with another plugin you can change the data dynamically. For example for the jQuery webTicker you can simply replace the content with the list items using javascript and the rotation will continue without halt. I have used this method on a financial website and works like a charm updating the data every few seconds to show the latest exchange rates. The scrolling and dimensions id done automatically per item; once it moves out of screen it is popped back in at the end of of the list. So the list should not break at any point in time
$("#ticker").jStockTicker({interval: 45});
from calling the jStockticker inside success method the scrolling stops and restarts from the begining.

Categories

Resources