jQuery .load() Callback - javascript

I'm trying to load some content with an AJAX call and AFTER the content is loaded, perform another action. In my example, that latter action is simply an alert but in my real-world example I'm attempting to focus on an input field.
$("#box").load("/favicon.png", function(response) {
alert('do after the load');
});
https://jsfiddle.net/u0cmmn5h/
As you can see in the fiddle, the alert fires BEFORE the favicon is actually loaded. Isn't the function supposed to fire AFTER the content has been loaded?

The callback on .load() executes upon an http response, not when the image is rendered client side.

Here is an example of using load on an image. Not sure what you have the load on a div.
The load method will be fired when the image src attribute changes and the image is successfully loaded (note if it fails this wont execute).
.load() jQuery
The load event is sent to an element when it and all sub-elements have been completely loaded. This event can be sent to any element associated with a URL: images, scripts, frames, iframes, and the window object.
$(function() {
$('img').load(function() {
alert('done after load');
}).attr('src', '/favicon.ico');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="box">
<img />
</div>

Related

Getting a jQuery function to fire

I have a very simple jQuery function
$('#bnAddDegree').click(function () {
alert("bnAddDegree Loaded");
});
I have broken my site into different pieces based upon what the user clicks. If they click on a tab in the menu to load a section I call a partial_html page and load the section into the center div. If I put the code above into the main page load it will not fire. If I add an external js file and load it when the page loads it will not fire, I think because the elements are not initialized yet. If I put it into an external js page that is loaded after the partial_html is loaded it will not fire. If I put it ON the partial_html page with a tag it DOES fire. If I put a simple javascript function
function testFile() {
alert("File Loaded");
}
In the places that the jQuery code will not fire it works fine.
Is there something special that I'm missing with jQuery?
When I load the javascrip file I use
$.getScript("js/biosketch.js")
And test it with the simple javascript file and it works fine but not the jQuery call.
You need to use delegated event handlers since you are modifying the DOM dynamically.
$(document).on('click', '#bnAddDegree', function () {
alert("bnAddDegree Loaded");
});

How to Make Jquery .load() function work once and Ajax request once?

When the page is loaded contents from the PHP file has to load, for that i am using JQuery .load() function, content is successfully loading but it keep loading, i can see it from chrome Developer tools. I have to load content only once.
var userName =$('#dT').data('uname');
$('#dT').load('load_table.php', {userName:userName});
So i tried another Jquery ajax method that also same as loads the contents continuously..
$(document).ready(function(){
function loadTable(){
var userName =$('#dT').data('uname');
$.ajax({
url:'load_table.php',
data:{'userName':userName},
success: function(results){
$('#dT').html(results);
setTimeout(loadTable,5000);
}
});
}
loadTable();
});
Above setTimeout function not working, any way to load content from PHP file only once?
I think in your first load attempt you are loading the html with the exact same code, so it will keep on loading itself infinity.
Doing it with ajax is much better, however if I were you I would move the settimeout outside the function itself. Currently it will only trigger if the initial call was successful, you want it to run every 5 seconds I am guessing. So where you call it the first time at the bottom, instead of just
loadTable();
You have:
setTimeout(loadTable,5000);
Now you do not need to do the settimeout in the success function.

$(document).ready not working in ajax page

I'm loading my page contents dynamically with ajax and I want to load certain .js files with a function. The .js file loads fine, but only before the next page has been loaded via ajax.
For example: from homepage to biography page:
1st loads the .js file
2nd: loads the biography page (via ajax)
It looks like that the ajax page is always on state document ready. So it wil trigger immediately the .js file, before it loads the content of the biography page via ajax.
$(document).ready(function() {
$(".element").click(function() {
jQuery.getScript("http://example.com/js/file.js");
});
});
I've manage to solve this problem temporary with a timeout, so that the .js file will load after 5 seconds, so after the page biography has been loaded.
$(".element").click(function() {
setTimeout(function() {
jQuery.getScript("http://example.com/js/file.js");
}, 5000);
});
How can I change the function so that it will load the .js file as soon as the biography page has been loaded (or any other page), instead of a timeout.
EDIT1:
I've added the ajax call here:
http://jsbin.com/ediFUca
AJAX allows you to specify a callback: a function to call when the request is finished.
Put your scripts/functions in the callback and it will execute when your seconds page has completed loading, effectively solving your problem:
$.ajax({
url: "test.html"
}).done(function() {
//do things in here that should be done after the AJAX call e.g:
jQuery.getScript("http://example.com/js/file.js");
});
As you mentioned in first line that you are loading contend dynamically so your predefined click handler will not fired for content that are added later.
So you need to use event delegation.
use jQuery.on(); for that.
Sample
jQuery(document).on('click',".element",function()
{
jQuery.getScript("http://example.com/js/file.js");
});

How to determine if an html div element is completed loaded

On clicking a load button in a jsp (1.jsp), another jsp(2.jsp) is loaded in a div element of the original jsp(1.jsp).
This loaded div jsp has some large datatable and html elements that take time to configure (a few seconds.) During this time it would be useful to show the user a loading dialog or wait screen as the jsp is not fully ready.
I tried using jquery modal as well as jquery show/hide as follows
$("#loadpage").show();
$("#divElement").load("2.jsp");
$("#loadpage").hide();
but the probelm is that the hide() is called before the 2.jsp is fully loaded.
How to keep a loading gif untill the 2.jsp is fully loaded????
Just use the call back function of the load function
$("#divElement").load("2.jsp", function () {
$("#loadpage").hide();
});
Callback Function
If a "complete" callback is provided, it is executed after post-processing and HTML insertion has been performed. The callback is fired once for each element in the jQuery collection, and this is set to each DOM element in turn.
For more information you can see the JQuery Documentation of load
EDIT (after comment):
If you want to check the error you can implement the function the following way :
function(response, status, xhr) {
if (status == "error") {
// Do something on error
} else {
$("#loadpage").hide();
}
}
you can pass a function in load. it will be get called once download of 2.jsp complete.
$("#divElement").load("2.jsp", function(){
// content is loaded
});

jQuery Mobile load second page from new html

Say I wanna load a new html file, with some jQuery pages, like this:
$.mobile.changePage("some_page.html");
If this html file has two pages inside, how do I load not the first, but the second page?
I Tried
$.mobile.changePage("some_page.html#second_page_id");
But it doesn't work.
Thanks
Dude try to make your second page element data-url as <div data-url="page.html&subpageidentifier">
in the target html page. and let me know is that really worked for you.
The $.mobile.changePage() function takes the first div with data-role="page" and loads it into the dom with an AJAX call. The best solution is to move the second page to the top of the html code.
Otherwise, if you want to decide to load the first or second page, you could put them in different files.
Maybe there's a way of calling the second page, but i have no idea of how to accomplish this.
You can manually grab the element you want:
//delegate the event binding for some link(s)
$(document).delegate('a.my-link', 'click', function () {
//show the loading spinner
$.mobile.showPageLoadingMsg();
//make the AJAX request for the link's href attribute
$.ajax({
url : this.href,
success : function (serverResponse) {
//get the data-role="page" elements out of the server response
var $elements = $(serverResponse).find('[data-role="page"]');
//you can now access each `data-role="page` element in the `$elements` object
$elements.filter('#page-id').appendTo('body');
//now use changePage to navigate to the newly added page
$.mobile.changePage($('#page-id'), { /*options*/ });
//hide the loading spinner
$.mobile.hidePageLoadingMsg();
},
error : function (jqXHR, textStatus, errorThrown) { /*Don't forget to handler errors*/ }
});
//stop the default behavior of the link, also stop the event from bubbling
return false;
});
But I have to say, with the way jQuery Mobile currently works, you're better off putting each data-role="page" elements in a separate document.
ทำแบบนี้ครับ
ออก
สำคัญคือให้ใส่ data-ajax="false"
คุณก็จะ changepage ได้จากต่างหน้า

Categories