jquery ajax call and hide function - javascript

I have the following script that works ok on the first page load. I am then calling a page again and the hide function does not work, and certain formatting is lost..
Any ideas. Is there a way using jquery live or delegate for instance.
$(document).ready( function() {
// Hide all subfolders at startup
$(".php-file-tree").find("UL").hide();
// Expand/collapse on click
$(".pft-directory A").click( function() {
$(this).parent().find("UL:first").slideToggle("medium");
if( $(this).parent().attr('className') == "pft-directory" ) return false;
});
});
How do I execute find("UL").hide(); again on ajax call.

In the ajax success handler just execute the below line
$(".php-file-tree").find("UL").hide();

Related

Bootstrap slide event not working inside AJAX success

This is my code, 'slide' event inside AJAX success call.
success: function(data) {
$('#my_container').html(data);
// I am getting' #mycarousel' successfully in to #my_container
$('#mycarousel').bind('slid', function(e) {
console.log('hi');
}
// tried 'slid.bs.carousel' too, no change.
// btw, I can see my 'slid' function under event listeners for that element.
// when I paste the above binding code in console again it shows the element too.
});
I want to print the 'hi' to console on slid event, which is not working now.
Thanks
Check whether you have multiple versions of jquery libraries loaded in the page.
Use $.fn.jquery to find the loaded version and cross check it with the jquery version you have included and see both are same.
After loading the carousel dynamically, you have to initialize it (as androbin suggested):
$('#my_container').html(data);
$("#mycarousel").carousel();
$('#mycarousel').bind('slide.bs.carousel', function (e) {
console.log('slide event!');
});
$('#mycarousel').bind('slid', function (e) {
console.log("slid event!");
});
Here you can see it working: http://jsfiddle.net/faw242a8/1/
Make sure the html you are pulling in via ajax contains a valid carousel.
Reference: Carousel - Bootstrap

How do I execute a javascript after Ajax load?

I need to add a class on after an ajax load. I first give a few elements a class "ready" which initiate a css transition. When the link li#menu-item-318 a gets clicked it removes the ready class which then reverses the css transition and then loads a new html document. On the Aja load I once again want to add the ready class to the same elements inserted by the Ajax call.
The code below has a callback to add the ready class, which works. But when the Ajax loads its sets the Ready class too early so there is no transition, even though my lines that is supposed to be drawn up is set.
I was thinking Its better I have a script for setting the classes on my transition elements inside the html that gets called by ajax to achieve my desired effect - but that doesn't work. So how do I do?
Demo: http://svensson.streetstylizm.com/ Click the photography - Polaroid link to se how it reverses the animation, loads the page and then just show the lines.
Code:
$(function () {
$('.v-line, .h-line, .nav, #ban_image img').addClass('ready');
});
$('li#menu-item-318 a').click(function (e) {
e.preventDefault();
var linkNode = this;
$('.v-line, .h-line, #ban_image img')
.removeClass('ready')
.one('webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend',
function (e) {
$(".js-pageTransition").load("photo.html .test> *");
});
});
You can use ajaxComplete():
$.ajaxComplete(function () {
// Something to execute after AJAX.
});
Have this as an example:
$( document ).ajaxComplete(function( event,request, settings ) {
$( "#msg" ).append( "<li>Request Complete.</li>" );
});
As said by Popnoodles, this executes when any AJAX call completes. So if you are looking for executing the code in one particular AJAX call, you need to use the success function.
The way to do this would be use the ajaxcomplete function in jQuery which is called implicitly after the completion of any ajax call.
The examples in this link should get you started
.ajaxcomplete() Function

Bind click to images loaded via AJAX

I've been having some trouble with this block of code, and I think I've finally narrowed the problem down. Here's the jQuery function...
$(document).ready(function(e) {
$('#formattingSection').load ('formattingdoc.html #formatting');
$('#loadFormatting').click(function() {
$('#formattingSection').load ('formattingdoc.html #formatting');
});
$('#loadSmileys').click(function() {
$('#formattingSection').load ('formattingdoc.html #smileys');
});
$('#formattingSection div img').click(function() {
var code = $(this).attr("title");
alert (code);
$('wallpost').val($('wallpost').val() + code);
});
});
Basically, it works like this. The page loads, we load part of a doc via AJAX. There are four buttons on the page, each one loads a new section via AJAX. When you click #loadSmileys, it will load via AJAX several images and display them in the DIV.
I'm binding a click() event to those images... but what I've found is that since the images aren't on the page at load time, the click event never gets bound. When I strip all the code away and load the images without AJAX, the click binds okay.
So... my question here... is there a way to bind the click event to the images AFTER they are loaded via AJAX?
For reference... I did make a jsBin HERE, but it's basically just hard coding the images to that I can see it works without the AJAX stuff going on.
Try:
$("#formattingSection").on("click","div img",function() {
var code = $(this).attr("title");
alert (code);
$('wallpost').val($('wallpost').val() + code);
});
As $.on attaches event handler to the parent and all events from children are delegated to the parent
Documentation
Yes, you totally can attach event handles to DOM nodes loaded on-the-fly. The trick is to use jQuery.get instead of .load. .get allows you to add an additional callback function that gets executed upon AJAX completion - the perfect place for you to add your $("#formattingSection div img") code. Here's what it would look like:
$('#loadSmileys').click(function() {
$('#formattingSection').get ({
url: "formattingdoc.html",
success: success
});
});
function success() {
$('#formattingSection div img').click(function() {
var code = $(this).attr("title");
alert (code);
$('wallpost').val($('wallpost').val() + code);
});
}
$('#formattingSection').load ('formattingdoc.html #formatting', function( response, status, xhr ) {
loading_completed();
});
function loading_completed()
{
$('#formattingSection div img').click(function() {
var code = $(this).attr("title");
alert (code);
$('wallpost').val($('wallpost').val() + code);
});
}
Try this
$('#loadSmileys').click(function() {
$('#formattingSection').load ('formattingdoc.html #smileys', function() {
$('#formattingSection div img').click(function() {
var code = $(this).attr("title");
alert (code);
$('wallpost').val($('wallpost').val() + code);
});
});
});
You should use the 'on' method. This can apply click handlers to elements created after the on method is called.
e.g.
$("#formattingSection").on("click","div img",function() {
...
}
As imges are added, they will automatically get the click handler functionality.
This question I asked helps explain the difference: jquery use of bind vs on click

Fancybox not closing after ajax call

I'm having trouble closing my fancy box in some cases after an ajax call.
$(document).ajaxStop(function() {
function(){$.fancybox.close()};
});
$(document).ajaxStart(function() {
$("a#load_gif").trigger('click');
});
Here's my code handling the fancy box. So my problem is that if the ajax call is very brief and fast the box doesn't close, however if the call is longer it closes automatically as it should.
I have found a fix which goes along the line of this
$(document).ajaxStop(function() {
setTimeout(function(){$.fancybox.close()},500);
});
But honestly that solution is not good looking. What can I do to make the fancy box close even if the ajax call is returned very fast? The length of the ajax call is variable depending on the number of rows it has to fetch.
Any help and/or suggestions are appreciated.
It seems like you have a race condition and maybe the fancybox isn't finished being created and doesn't have it's close function defined yet when your AJAX call is attempting to fire off that close function.
I recommend a 2 step process that triggers the fancybox to close. Create 2 global variables ajaxStop = false; and fancyboxDone = false;
create a function like:
function closeFancyBox(){
if(ajaxStop && fancyboxDone){
$.fancybox.close();
ajaxStop = fancyboxDone = false;
}
}
Then change your ajax stop to :
$(document).ajaxStop(function() {
function(){
ajaxStop = true;
closeFancyBox()
};
});
And finally add an onComplete function to your fancybox that does the same as the ajax Stop but sets fancyboxDone = true instead of ajaxStop.
So now no matter which one finishes first and second they will be able to check on each other's status and fire the close appropriately.

Can I call $(document).ready() to re-activate all on load event handlers?

Does anyone happen to know IF and HOW I could re-call all on-load event handlers? I'm referencing some .js files that I DON'T have control over, and these .js libraries do their initialization in $(document).ready(), and unfortunately don't provide any easy function to re-initialize.
I'm currently trying to replace a large div block with content from an ajax call, and so I have to re-initialize the external libraries. So, it would be nice just to call $(document).ready() in order to re-initialize EVERYTHING.
So far, I've tried this on the ajax call:
success: function(data) {
alert('1'); // Displays '1'
$('#content').html(data);
alert('2'); // Displays '2'
$(document).ready();
alert('3'); // Does not display
}
Calling $(document).ready(); fails quietly too. JavaScript console shows no errors. Does anyone know if this is possible (without modifying javascript library files)?
Since you asked how to do it without modifying the external JS files, I'll answer that way. I've traced through the .ready() function in jQuery in the debugger and it appears that the root function that gets called when the page is ready is this:
jQuery.ready();
But, it appears you cannot just call it again to accomplish what you want because it appears that when it fires the first time, it unbinds from the functions that were previously registered (e.g. forgetting them). As such, calling jQuery.ready() manually a second time does not retrigger the same function calls again and I verified that in the debugger (breakpoint was only hit once, not second time).
So, it appears that you cannot solve this problem without either changing the jQuery implementation so it doesn't unbind (to allow multiple firings) or changing each piece of ready handler code to use your own events that you can fire as many times as you want.
I did something like:
// When document is ready...
$(function(){
onPageLoad();
});
function onPageLoad(){
// All commands here
}
Now I can call this function anytime I need.
A simple way to achieve this is just to invent your own event like this:
$(document).bind('_page_ready', function() { /* do your stuff here */});
Then add this:
$(function() { $(document).fire('_page_ready'); }); // shorthand for document.ready
And last, whenever you need to run it again you simply call this:
$(document).fire('_page_ready');
[Edit]
If you really can't edit the external script-files I've made a jsFiddle that makes what you want to do possible, you can take a look at the code here: http://jsfiddle.net/5dRxh/
However, if you wan't to use this, it's important that you add this script RIGHT AFTER you include jQuery, like this:
<script src="jquery.js" type="text/javascript"></script>
<script>
//script from jsFiddle (only the plugin part at the top).
</script>
<!-- All the other script-files you want to include. -->
You can trigger document.ready second time if you change entire body content:
$('body').html($('body').html())
I don't think that this can be done since jquery unbinds the ready event after it is executed. From the source:
// Trigger any bound ready events
if ( jQuery.fn.trigger ) {
jQuery( document ).trigger( "ready" ).unbind( "ready" );
}
You can do this simple.
Make a function:
function REinit() {
/// PLACE HERE ALL YOUR DOC.READY SCRIPTS
}
Place just the Reinit() function inside doc.ready:
$(document).ready(function(){
REinit();
});
then after an ajax action just call
REinit();
I think it is straight forward to just change the ready event to pjax success
Change it from:
$(document).ready(function() {
// page load stuff
});
To:
$(document).on('ready pjax:success', function() {
// will fire on initial page load, and subsequent PJAX page loads
});
This will be what you want, just hold the ready event until you are really ready.
https://api.jquery.com/jquery.holdready/
Or, try this:
jQuery.extend ({
document_ready: function (value) {
$(document).ready (value);
$(document).ajaxComplete (value);
}/* document_ready */
});
And instead of defining a function by saying:
$(document).ready (function () { blah blah blah });
say:
jQuery.document_ready (function () { blah blah blah });
Explanation:
Any function loaded to "document_ready" will be automatically loaded into both "$(document).ready ()" and "$(document).ajaxComplete ()" and will fire under both circumstances.
I just had the problem that my ajax code only worked if it gets called by the $(document).ready(function(){}); and not in a regular function, so I couldn't wrap it.
The code was about loading a part of my page and because of some loading errors I wanted it to be called again after a timeout.
I found out that the code doesn't have to be in the $(document).ready(function(){}); but can be run by it and can also be called by itself.
So after I read many solutions from different pages now I've got this code mixed together:
$(document).ready(loadStuff);
function loadStuff(){
$.ajax({
type: "POST",
url: "path/to/ajax.php",
data: { some: data, action: "setContent"},
timeout: 1000, //only one second, for a short loading time
error: function(){
console.log("An error occured. The div will reload.");
loadStuff();
},
success: function(){
$("#divid").load("path/to/template.php"); //div gets filled with template
}
});
}

Categories