Using .load in JavaScript - javascript

I am using .load() function in JavaScript and I'm working with JSP java files. I am loading a page like this in JavaScript
$("#body").load("livestatus #status")
The problem is the div I'm trying to load doesn't load immediately on page load because it contains some data from APIs, so there's a one second delay but my code doesn't accommodate that delay.

Try to put your code in document.ready block or if you are making an ajax request then put your code in Ajax success function

If you use jQuery and it just not initialized for some element, you can use
$(function() {
$("#body"). // ... your code
});
If it calls through some time and you can't track when exactly, you can use live listeners on some event. Like, click on this element.
$("body").on("click", "#body", function() {
// your code
});
$("body") can contain any parent element which had loaded before jQuery.
Or you can load 1px image with you code which loads after main code and track when it will load.
<div id="body">
<!-- your markup -->
<img class="loading-status-img" src="../path_to_1px_small_image.png" style="display:none">
<img class="loading-status-img-2" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVQI12NgYAAAAAMAASDVlMcAAAAASUVORK5CYII=" style="display:none">
<!-- your markup -->
</div>
<script>
$("body").on("load", ".loading-status-img", function() {
// execute you code here after #body will load
});
</script>
The second image is encoded with base64.
[UPD] old version of jQuery have another syntax. More: http://api.jquery.com/live/

Related

How do I change placeholder content in javascript per page

How do I update content loaded with Jquery .load() with javascript?
I'm using two placeholders on every page: one with the navigation bar, and one with the main skeleton of the content, like this:
<body>
<div id="nav-placeholder">
</div>
<div id="content-placeholder">
</div>
</body>
The nav bar and content are both in seperate files and are loaded into the pages with an external javascript file like this:
$(function(){
$("#nav-placeholder").load("nav.html");
});
$(function(){
$("#content-placeholder").load("content.html");
});
So far, it all works nicely. Now, I'm trying to alter the content separately for each page (with JS)
Part of content.html is for example
<h2 id="subheader1">Title</h2>
I'm trying to change the #subheader1 content in the javascript file like so:
$(function(){
$("#nav-placeholder").load("nav.html");
});
$(function(){
$("#content-placeholder").load("content.html");
});
$(document).ready(function() {
document.getElementById("subheader1").outerHTML = "test" ;
});
but that doesn't work (this is aimed at all pages, but it still doesn't work). Probably because it's only seeing the placeholder DIV in index.html and not it's content?
I tried placing the subheader1 div in the index.html to test, and then it did work, but that would take away the efficiency of the placeholder.
Is there any way to do this (or another way to be more efficient with pages with the same (DIV) layout but different text?)
Thanks!
The load method is not synchronous, so
$(document).ready(function() {
document.getElementById("subheader1").outerHTML = "test" ;
});
is executed before the html is loaded in the page.
The doc suggest using a callback function.
it is executed after post-processing and HTML insertion has been performed
I had success using this in my js file:
$(document).ready(function() {
$(function(){
$("#nav-placeholder").load("./nav.html", function() {
document.getElementById("insideNav").outerHTML = "It works !" ;
});
});
});
with <h2 id="insideNav">Original Nav Bar</h2> in my nav.html.

Load HTML within AJAX call

I'm having some difficulty with a Javascript function I am writing. The basic function of the script is that when a specific AJAX function is called and returns successful, it loads some HTML from a file and inserts that HTML into a on the main page and then (once loaded), fades in the parent div.
jQuery.ajax({
type: "POST",
url: "fns/authenticate.php",
data: dataString,
success: function (data) {
if (data=='1') {
jQuery("#authlogin").fadeOut(500, function(){
$(this).remove();
jQuery("#result").load("fns/logic.html", function() {
jQuery('#authtrue').fadeIn(1000);
});
});
} else {
jQuery('#details-error').fadeIn(200);
}
}
});
return false;
Now the AJAX seems to function properly, in that it will execute under the correct conditions and fade out and in the correct divs, the problem seems to be that the content isn't being loaded from logic.html or it is not being bound to the #result div correctly.
The main page's html looks like:
<div id="authlogin">
<!-- HTML form -->
</div>
<div id="authtrue" style="display: none;">
<div id="result"></div>
</div>
Any help would be much appreciated.
This is one of those things that you must troubleshoot yourself, because we do not have access to your fns/logic.html and therefore cannot test fully.
However, some thoughts:
(1) The basic logic of your .load() success function seems correct. Here is a jsFiddle that approximates the AJAX success function's logic. I substituted .html() for .load() because jsFiddle cannot do ajax. Anyway, assuming that .load() is doing what it should, that part should be working.
(2) You may already know this, but note that .load() is shorthand for $.ajax() -- as are .post() and .get(). You might find $.ajax() easier to troubleshoot as the code block is more structured. As a general rule, troubleshooting the shorthand constructions is slightly more abstract/difficult than troubleshooting $.ajax()
(3) Use developer tools in Chrome (press F12 key) to verify that the contents of logic.html have been inserted into the #result div. You might find, as I did in playing with my jsFiddle, that the contents were injected but the #authtrue div remained hidden. At least you will know that the logic.html document has been found and contents inserted. Knowing exactly where the problem is, finding/fixing the rest might now be trivial.
(4) Does your logic.html file include unnecessary header information? If so, you can strip it out by only inserting the BODY of the document, or a top-level containing div. See this section of the jQuery docs:
jQuery("#result").load("fns/logic.html #container", function() {//CALLBACK IN HERE});
(5) It would be a smart idea to create a test document that just and only loads the logic.html document, using various methods:
Method A: Using PHP (or whatever server-side language you use)
<div id="authlogin">
<!-- HTML form -->
<input type="button" id="mybutt" value="Click Me to Start" />
</div>
<div id="authtrue" style="display:none;">
<div id="result"><?php include 'logic.html'; ?></div>
</div>
Method B: Using load()
HTML:
<div id="authlogin">
<!-- HTML form -->
<input type="button" id="mybutt" value="Click Me to Start" />
</div>
<div id="authtrue" style="display:none;">
<div id="result"></div>
</div>
jQuery:
jQuery('#authtrue').show();
jQuery("#result").load("fns/logic.html");
(6) Ensure you do not have a typo in the destination element jquery selector: If no element is matched by the selector — in this case, if the document does not contain an element with id="result" — the Ajax request will not be sent. (from the docs)
I managed to fix this myself, thanks to the help of everyone here. It ended up being a browser caching problem. As soon as I cleared the cache everything magically worked.

Dynamically generated script not working

I have a contenteditable div where you type javascript which gets outputted into an empty script tag.
<div contenteditable="true" id="script-generator"></div>
<div id="save-script">Save</div>
<script type="text/shorthand" id="script">
</script>
So you write your script in the div, click save and I have some JS which gets the html of the contenteditable div and adds it to an empty script tag.
$('#save-script').click(function() {
var script = $('#script-generator').html();
$('#script').html(script);
});
So far this works. But the generated script has no effect. The browser must not recognise the script because it wasn't there on page load? How do I make the script take effect without reloading the page?
Note: The type/shortand on the script is because I'm using a plugin which converts shortand words into actual Javascript. So the user would just need to write shorthand into the contenteditable div, and the plugin would convert that to JS. This might be adding to the problem?
I don't think it works to modify an existing <script> element. If you want the script to be executed you need to add a new element.
$('#save-script').click(function() {
var script = $('#script-generator').html();
$("#script").text(script);
ShortHand.parseScripts();
});
Correct - you need to create the script tag to have it execute after load.
$('head').append($('<script />', {html: script}));
...which means you can remove your empty script tag.
I have set up a test that's similar to what you have been looking for. Take a look and see if that helps.
Working Demo
Test code:
<div id="script" style="display:none">
alert(4+4);
</div>
<input id="sLoad" type="button" value="Load/Execute Script" />
$('#sLoad').click(function(){
//You may want to append to the head
$('<script/>').append( $('#script').html() ).appendTo('#script');
});

document.ready working only once on page load

I have the following code in a .tpl file ("comment_form.tpl"). This file is included in 3 different .tpl files ("file_a", "file_b" and "file_c") once each. And finally these 3 files are included in another .tpl file ("somefile.tpl").
<script type="text/javascript">
$(document).ready(function Hide() {
document.getElementById('div').style.display = 'none';
</script>
So basically, the "comment_form.tpl" is loaded thrice in "somefile.tpl" like so:
.....
</div><!-- .span9 -->
{include file="includes/file_a.tpl"} // includes "file_a.tpl" which already includes "comment_form.tpl" (which contains the code).
</div>
.....//some code
{include file="includes/file_b.tpl.tpl"} // "includes file_b.tpl" which already includes "comment_form.tpl" (which contains the code).
The issue is, the code works the first time. As in, out of the three places where the "comment_form.tpl" is loaded in "somefile.tpl", the target 'div' is hidden only the first time. At the next two places the form (div) isn't hidden.
I hope I am clear enough. What could be the reason??
It is perfectly legal to have multiple $(document).ready(function() {}) calls throughout your page.
It seems that you are hiding your element by ID. Note that IDs must be unique, and if you use the same ID multiple times (#div in your example), only ever the first is selected by getElementById(). That's what you are experiencing.
You must give each <div> a unique ID or group them together with a CSS class and hide the whole class.
Here is an example using a CSS class:
<div class="comment_form">some content</div>
<div class="comment_form">some content</div>
<div class="comment_form">some content</div>
<script type="text/javascript">
$(document).ready(function () {
$('.comment_form').css({'display' : 'none'});
}
</script>
By the way it's far more efficient to directly use CSS for the initial 'hidden' state of your <div>. There is no need to execute JavaScript on page load at all:
<style>
.comment_form { display: none; }
</style>
<div class="comment_form">some content</div>
You can still change the display property of your element later via JavaScript in an onClick event, for example.

javaScript not working for page loaded by jquery load function

Page 1
<html>
<head>
<script src="jquery-1.8.3.js" type="text/javascript"></script>
</head></head>
<body><div id="main"></div> </body>
<script>$('div[id=main]').load('page2.php')
$('span[id*=temp]').on('click',function(){
alert(this.id); }); //this block of code not working!!
</script>
</html>
Page 2
<div>
<span id="temp">
this is demo
</span>
</div>
Basically i want to load page2 again in main div when tag is clicked but am not able to fetch the id of the tag in page one,script of page1 not working for page 2 items or tags
You are trying to bind the event right after the AJAX call, so the element doesn't exist yet. The call is asynchronous, so it doesn't stop the code execution to wait for the response.
Either bind the element after the content has loaded, using the success callback of the load method:
$('div#main').load('page2.php', function(){
$('span[id*=temp]').on('click', function(){
alert(this.id);
});
});
or use a delegate to bind the event to the parent element:
$('div#main').load('page2.php');
$('div#main').on('click', 'span[id*=temp]', function(){
alert(this.id);
});
Because you need to specify the parent selector to taking into account the elements created dynamicaly.
Exemple :
$("#main").on('click', 'span[id*="temp"]', function() {alert('Handler is working!');})
Here is a good related question : jQuery 1.7 on() and off() methods for dynamic elements

Categories