Very Simple jQuery .load Example Not Working - javascript

I think this is a very simple question, but I can't seem to get it to work. I need to use JavaScript (specifically jQuery, apparently) to grab some content from a page, and pull it into another page. I've researched this quite a bit, but can't seem to get even a very simple example to work.
Here is the page I'm trying to get content from:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Test</title>
</head>
<body>
<p>This is the test html page.</p>
</body>
</html>
Here is the page I'm trying to use to pull the content:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>PullData</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js">
</head>
<body>
<ol id="result"></ol>
<script type="text/javascript">
$('#result').load('test.html');
</script>
</body>
</html>
When I open the page it doesn't seem to do anything. I'm basically trying to follow the examples from jquery.com: http://api.jquery.com/load/
Both html pages are in the same folder somewhere on my C drive.
What am I missing?
Thanks in advance for your help!

What browser are you using?
Because of same-origin policy, some browsers won't permit AJAX requests to file:/// URLs, even if the original file was loaded that way. I know this is true of Chrome, but haven't tested others.
What does your .load() error handler say? Oh...

It seems to make logical sense.
Checking the API on load you may want to see if it actually loads, or if it encoutners an error
$("#result").load("/not-here.php", function(response, status, xhr) {
if (status == "error") {
var msg = "Sorry but there was an error: ";
$("#result").html(msg + xhr.status + " " + xhr.statusText);
}
});
API LINK: http://api.jquery.com/load/
sometimes the debugging information is a good first step to any solution.

You have your script tags at the end of your page, which means the enclosed JS will be invoked as soon as the browser reaches it, which may not be before the DOM is ready (which means the <ol> might not be set up to get the content of test.html). Try enclosing your load in a $(document).ready() callback as follows:
<script type="text/javascript">
$(document).ready(function() {
$('#result').load('test.html');
});
</script>
Also why are you inserting a full HTML page into an ordered list? You should try an HTML snippet (no head & body tags) into a content holder such as <div> or <span> where it will be semantically correct.
If none of these things work, attach a callback as follows:
$('#result').load('test.html', null, function(responseText, textStatus, xhr) {
alert(textStatus); // see what the response status is
});

Where is the closing script tag?
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js">
</head>
Your code needs to be
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
</head>

You must first check if your HTML is ready.
$(document).ready(function() {
$('#result').load('test.html');
});

To ensure #result1 is loaded, you need a document.ready event handler:
<script type="text/javascript">
$(document).ready(function(){
$('#result').load('test.html');
});
</script>
Hope this helps. Cheers

Related

How can I run JavaScript function in my HTML

I wrote a function in JS code, and I want to run it from HTML, but I don't see any reaction, when I run the site.
I will show you example of html code and js code.
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="test.js">
<script src="test.js"></script>
</head>
<body onload="add()">
<p id="add2"></p>
</body>
</html>
Here starts JS code
function add(a,b,c,d) {
return a + b + c + d;
}
document.getElementById("add2").innerHTML = add(5,10,15,20);
I hope I wrote it clearly and someone will tell me, what did I do wrong?
Your JavaScript code is in the head, which is before the body and everything else, so the JavaScript runs before the p element has been created (html is run line by line). To fix this issue, you can try putting the JavaScript at the end of the document, for example after body.
When a browser loads an HTML page, it reads your HTML from top-to-bottom.
So ordering is important.
There are complexities of course. I'm not talking about deferred or asynchronous scripts here. But the top-to-bottom simplification helps us understand your problem.
Your script is inside test.js, so it will be loaded and run before [body] is ready.
But test.js has this line:
document.getElementById("add2").innerHTML = add(5,10,15,20);
This line is not inside a function, so the browser will try to run it immediately.
The call to add() will work because it has been declared in the file. But document.getElementById("add2") will not, because it is an instruction to access the following HTML in the [body]:
<p id="add2"></p>
But the [body] has not been "read" yet, so the JavaScript DOM API does not know about it.
However, you have partially solved the problem already using the onload attribute of the [body] tag. You've just used the wrong function with it.
That onload is an instruction to run a function after [body] has been completely read. So if you changed your document.getElementById line to be inside a function:
function runWhenBodyHasLoaded () {
document.getElementById("add2").innerHTML = add(5,10,15,20);
}
And told the [body] tag to run the function after everything has loaded:
<body onload="runWhenBodyHasLoaded()">
Then <p id="add2"></p> will be ready in time to access it with document.getElementById.
Or with jQuery:
https://jsfiddle.net/bdgu8s4h/1/
Also consider loading your JS at the end (of body)
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="test.css">
</head>
<body>
<p id="add2"></p>
<script type="text/javascript" src="test.js"></script>
</body>
</html>
JS (jQuery):
$(document).ready(function() {
function add(a,b,c,d) {
return a + b + c + d;
}
$('#add2').html(add(5,10,15,20));
});
Hope this also helped, cheers

How can I get the content of a loaded file (with script or link)

I was wondering, how I get the content of a loaded script, stylesheet, ... bye an accessing an id set on the element.
Example:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Demo</title>
<script src="../jquery-1.8.3.min.js"></script>
<script id="test" src="test.txt" type="text/isis-template"></script>
<!-- File contains "Hello world" -->
<script>
$(function () {
$('#test').GET_CONTENT_OF_LOADED_FILE
});
</script>
</head>
<body>
</body>
</html>
Background: I want to load HTML templates (e.g. for mustach, knockout), but don't want to write them into the page, I'd rather have them in a seperate file. Now I saw that I can load any file with the script or link tag, so I was testing if I can load them like this....
Any comments why this might be a bad idea or how it can be done better are appreciated.
Try using load()
$(function () {
$('#test').load('yourfolder/test.html', function(resp){
alert(resp);
});
});
If you have already load the contents in some html element
contents = $('#test').html();
So you want the content of text/isis-template file when document is ready?
You are lucky because this file doesn't fall for CORS but mine(the answer i was looking for and came here today) do.
Well just do ajax!
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Demo</title>
<script src="../jquery-1.8.3.min.js"></script>
<!-- File contains "Hello world" -->
<script>
$(function () {
$.ajax({ url: "test.html"})
.done(function(cont) {
var GET_CONTENT_OF_LOADED_FILE=cont;
});
});
</script>
</head>
<body></body>
</html>
If you use debug tools and see the network activity, you will see that it does not load the external files (since it is not a text/javascript, and the browser does not know how to handle it)
(wrong test on my part, was testing local files)
So you only have a tag there with an id and an external resource in the src attribute. Treat it as just metadata.
You will have to manually load the resources
something like this
// load external template resources
$('script[type="text/isis-template"]').each(function(){
$(this).load(this.src);
});
For actual use you would need to make sure the templates are loaded before you try using them..

Javascript: Can't get element using getElementById [duplicate]

This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 6 years ago.
Ok. I need fresh eyes because I'm still on this s***d problem for one hour!
Here is my simple HTML code (testssio.html) that include javascript script:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var ssio = document.getElementById('ssio');
ssio.html = "it finally works!";
</script>
</head>
<body>
<div id="ssio"></div>
</body>
</html>
But it doesn't work! Using the debugger, I get:
Uncaught TypeError: Cannot set property 'html' of null /testssio/:6
Does anyone get it? I know it's not the correct place to look for debugging help, but I'll be crazy if I don't get it! So please, any help?
Tahnks in advance.
The reason for this is that scripts in the head load before the page is rendered. This means your content is not yet rendered and therefore not a part of document.
If you want to see this work, try moving your script below the element renders, like this:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="ssio"></div>
<script type="text/javascript">
var ssio = document.getElementById('ssio');
ssio.innerHTML = "it finally works!";
</script>
</body>
</html>
A more standardized way of doing this is with events. Many people use jQuery but it can be done with plain js. This would mean changing your script like this:
<script type="text/javascript">
function WinLoad() {
var ssio = document.getElementById('ssio');
ssio.innerHTML = "It finally works!";
}
window.onload = WinLoad;
</script>
This way you can still leave it in the <head>.
Also, using .html is from jQuery. It is generally used as .html(content). If you want to use the plain javascript version use .innerHTML = content.
I mention jQuery so much because it is a highly used API. This quote is from their site:
jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development. jQuery is designed to change the way that you write JavaScript.
Your code is running too early before the DOM is loaded and thus document.getElementById() doesn't find the element in the document yet.
You can either move your script tag down to right before the </body> tag or you can wait for the DOM to load before running your code with either the window onload event or a DOMReady event.
There are two errors here. First, you need to put the SCRIPT tag after the element. Second, it's not .html, but .innerHTML. So here is the corrected code:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="ssio"></div>
<script type="text/javascript">
var ssio = document.getElementById('ssio');
ssio.innerHTML = "it finally works!";
</script>
</body>
</html>
you can use something like this
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
document.onload= function(){
var ssio = document.getElementById('ssio');
ssio.html = "it finally works!";
}
</script>
</head>
<body>
<div id="ssio"></div>

Why document.ready waits?

I know that Document.ready - DONt wait for images to download.
So why it does here ?
http://jsbin.com/ehuke4/27/edit#source
(after each test - change the v=xxx in the img SRC)
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
alert('0');
});
</script>
</head>
<body >
<img src='http://musically.com/blog/wp-content/uploads/2011/04/Google-Logo.jpg?v=42333' />
</body>
</html>
I think, the problem comes out from JSBin.com
Because, when you try this example on JSFiddle.net, it works properly
http://jsfiddle.net/vqte9/
It has to do with the fact that you're using "alert()", I think, though I'm not 100% sure why. If you change your code like this:
<body>
<div id='x'></div>
<img ...>
</body>
<script>
$(function() { $('#x').text("hello there"); });
</script>
you'll see that the text is filled in before the image loads.
edit — I don't know why this would make a difference, but I notice quite different behavior when I set up the ready handler with:
$(function() { whatever; });
and:
$(document).ready(function() { whatever; });
Now that's not supposed to be the case; the two forms are supposed to do exactly the same thing, as far as I know. However, they don't seem to. Here is a jsbin example that sets up the ready handler with the first form, and here is one that uses the second one. They behave very differently for me. I'll have to check the jQuery source to figure out how that can be true.
Here is the jQuery documentation explaining the equivalence of $(handler) and $(document).ready(handler).

How to get scripts to fire that are embedded in content retrieved via the jquery load() method?

I have found several other questions here on S.O. (and the web in general) that ask roughly this same question, but the answers always seem to suggest other ways of structuring code that avoid the need for addressing this underlying issue.
For example, many people suggest (and a good suggestion, I agree) to put your code in the jquery load method's callback, on the calling page and not the called page. However I have unique scripts that may appear in certain resources, so I would not want to do that for every load and nor do I necessarily know what these scripts will be.
Here is a test setup to demonstrate what I'm trying to do. The short summary is that when I load partial.htm from main.htm, its script does not fire.
main.htm:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>main file</title>
</head>
<body>
<ul id="links">
<li>some page1</li>
<li>some page 2</li>
<li>some other partial page</li>
</ul>
<div id="panel" style="display:none; padding:20px; background-color:#CCC;">
LOADED CONTENT WILL GO HERE
</div>
<script type="text/javascript" src="/path/to/jquery-1.3.2.min.js"> </script>
<script type="text/javascript">
$(function(){
$('#links a').click(function() {
var $panel = $('#panel');
$panel.show();
$panel.html('Please wait...');
var href = $(this).attr('href');
$('#panel').load(href + ' #content');
return false;
});
});
</script>
</body>
</html>
OK, very simple functionality on this page. Imagine there are many more links, and some of them may require scripting while others do not.
Here is partial.htm:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>partial file</title>
</head>
<body>
<div id="content">
<p>Hey, I am the partial file!</p>
<script type="text/javascript">
alert('I am some JS in the partial file! But sadly I do not execute...');
</script>
</div>
<div>
I am some other content on the page that won't be included by jquery.load()...
</div>
</body>
</html>
Notice that my script in partial.htm does not fire. So, my question remains: how to get this to fire, excluding any answers that tell me to put this in the .load() method's callback. (This would be because I may not have the fore-knowledge of which scripts these partial pages may contain or require!)
Thank you!
Update #1:
I suppose an acceptable answer is simply "you can't." However, I'd like to know if this is definitively the case. I haven't been able to find anything that officially states this yet.
Also, when I use firebug to inspect the panel region afterwards, there is no script element present at all. It is as if it is being parsed out by load.
Update #2:
I've narrowed this down to be a problem only when using the selector as part of the href. Loading the entire "somepage.html" will execute the script, but loading "somepage.html #someregion" does not.
$panel.load('somepage.html'); // my script fires!
$panel.load('somepage.html #someregion'); // script does not fire
I'm going to try and hunt down why this may be the case in the jquery source...
Well it seems that this is by design. Apparently to make IE happy, the rest of us suffer. Here's the relevant code in the jquery source:
// See if a selector was specified
self.html( selector ?
// Create a dummy div to hold the results
jQuery("<div/>")
// inject the contents of the document in, removing the scripts
// to avoid any 'Permission Denied' errors in IE
.append(res.responseText.replace(/<script(.|\s)*?\/script>/g, ""))
// Locate the specified elements
.find(selector) :
// If not, just inject the full result
res.responseText );
I'm wondering if, instead of just stripping out the scripts, I could modify the jquery source to include them in some other way that makes IE happy? I still have yet to find anything else on the web discussing this matter, I'm sure I'm not the only person stumped by this?
I have run across issues before with IE not running injected <script>s that didn't contain the defer attribute. This discussion thread has some good information about the topic: innerHTML and SCRIPT tag

Categories

Resources