$(document).ready not working in ajax page - javascript

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

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

jQuery .load() Callback

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>

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.

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

Execute JavaScript function with externally loaded link

I'll admit the title is a bit confusing but it was hard to come up with a better one.
Ok, so What I have is 3 pages, first is the main page that the user loads up and the other 2 are ones that are going to be loaded into the main page with jQuery.
Here is the JavaScript code on the first page:
$(document).ready(function(){
$("#mainWrap").css({ width:"300px", height:"200px" });
$("#mainWrap").load("modules/web/loginForm.php");
$('[name=loadRegisterForm]').click(function() {
$("#mainWrap").load("modules/web/registerForm.php");
});
});
First of all it loads the login form into the page and then it listens for a link to be pressed which will then load up the register form in its place if it is pressed.
The link is in the login form that gets loaded, but unfortunately it doesn't work. What am I doing wrong?
I've tried placing the link on the main page with the JavaScript code and it does work, so is it just the fact that loading the link after the JavaScript has all ready been loaded going to leave it not working?
You need to have a callback function for the first load call. In side that call back is where you would set the click handler for the $('[name=loadRegisterForm]') element. Basically,
you are binding a handler to an element that does not exist until the first load is complete.
$(document).ready(function(){
$("#mainWrap").css({ width:"300px", height:"200px" });
$("#mainWrap").load("modules/web/loginForm.php", null, onLoadComplete);
});
function onLoadComplete()
{
$('[name=loadRegisterForm]').click(function() {
$("#mainWrap").load("modules/web/registerForm.php");
});
}

Categories