javascript will not make web requests - javascript

I am using an html document in my firefox web browser and is a file on my machine and Ive tried looking at web requests but it is showing none. I know for sure I have internet here is a reproduceable code below
<!DOCTYPE html>
<h1>StackOverFlow</h1>
<script src="js/jquery.min.js" language="javascript">
$.getJSON('https://jsonip.com/', function(data) {
document.writeln("<p> " + JSON.stringify(data, null, 2) + "</p>");
});
</script>

You need to have two <script> tags - one for jQuery and one for your code:
<script src="js/jquery.min.js"></script>
<script>
// Your code here
</script>

Related

Why does this code work on a separate file but not inline

This question may seem silly, but I really can't find out what the problem is. Initially I have a .js file only with this function that adds an audio to the page:
function addAudio(id_name, audio_filepath) {
var audio = $('<audio />')
.prop('id', 'audio' + id_name)
.prop('src', audio_filepath)
.text("Your reader doesn't support audio.");
$('body').append(audio);
$('#' + id_name).click(function () {
audio.get(0).play();
});
}
And it's being called in the html like this:
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
</head>
<body>
<!-- some content here -->
<button id="test">Play</button>
<!-- reference to lib containing jquery -->
<script type="text/javascript" src="js/lib.min.js"></script>
<!-- script where the function addAudio resides -->
<script type="text/javascript" src="js/add-audio.js"></script>
<script type="text/javascript">
$().ready(function() {
addAudio('test', 'audio/01-test.wav');
});
</script>
</body>
</html>
And that works fine. The problem is when I try to move the function out of the file and put it inline in the script tag. In that case, when I click the button, the console prints Uncaught TypeError: Cannot read property 'play' of undefined.
This is the modified code:
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
</head>
<body>
<!-- some content here -->
<button id="test">Play</button>
<!-- reference to lib containing jquery -->
<script type="text/javascript" src="js/lib.min.js"></script>
<script type="text/javascript">
function addAudio(id_name, audio_filepath) {
var audio = $('<audio />')
.prop('id', 'audio' + id_name)
.prop('src', audio_filepath)
.text("Your reader doesn't support audio.");
$('body').append(audio);
$('#' + id_name).click(function () {
audio.get(0).play();
});
}
$().ready(function() {
addAudio('test', 'audio/01-test.wav');
});
</script>
</body>
</html>
Trying to isolate the error, I found out that when the function is in the .js file, the variable audio is a jquery object [audio#audiotest], but when the function is inline, that variable is the object n.fn.init {}.
Why does that happen?
EDIT
I've noticed that that happens because it's in a xhtml file (I'm making an ebook in epub3 format). If I change the file to html it works again. But that is odd, because audio tags are supported in xhtml (you can check the specification here: http://www.idpf.org/accessibility/guidelines/content/xhtml/audio.php), and like I said, it works if the function is in a separate file. So why inline does not?
I think the issue is with your file reference. When I put your code into jsfiddle it appears to work referencing a wav file on the internet.
https://jsfiddle.net/ur64L8uh/
function addAudio(id_name, audio_filepath) {
var audio = $('<audio />')
.prop('id', 'audio' + id_name)
.prop('src', audio_filepath)
.text("Your reader doesn't support audio.");
$('body').append(audio);
$('#' + id_name).click(function () {
audio.get(0).play();
});
}
$().ready(function() {
addAudio('test', 'http://download.wavetlan.com/SVV/Media/HTTP/WAV/Media-Convert/Media-Convert_test1_Alaw_Mono_VBR_8SS_16000Hz.wav');
});
}
I found the answer, people. Thank you all for your attention and help, and sorry for the inconvenience. I was thinking about deleting this question, but I'm going to answer it to help those who might pass through the same thing.
According to Mozilla Foundation, using inline javascript in XHTML is troublesome: (https://developer.mozilla.org/en-US/docs/Archive/Web/Properly_Using_CSS_and_JavaScript_in_XHTML_Documents_/Examples#Example_1)
JavaScript typically contains characters which can not exist in XHTML outside of CDATA Sections.
So I solved the problem changing the line $('<audio />') to $('&t;audio /gt;')

Javascript Not Working in HTML - In a Variety of Ways

Is it possible to load javascript without jQuery? I spent the better portion of yesterday evening simply trying to create the most basic HTML page with working CSS and Javascript and - despite the numerous methods I have tried - none of them have worked. Here is my basic HTML page:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>title</title>
<link rel="stylesheet" href="style.css">
<script src="script.js" type="text/javascript"></script>
</head>
<body>
<div>On</div>
<input type="button" onclick="popup()" value="Click Me!">
</body>
</html>
This is being hosted locally on XAMPP, the page displays fine and the CSS works fine, the javascript is in the same directory as the html page and works fine when written inline with the HTML. However the js does not work in any of the following scenarios when trying to include it as an externality:
When application/javascript is used above it still doesn't work. All I receive in either case (in the Firebug script window) is "popup()" and that's it. Here is the script.js file:
function popup() {
alert("Hello World")
}
This js also doesn't work (I tried it even though I'm not parsing XML):
//<![CDATA[
function popup() {
alert("Hello World")
}
//]]>
nor this:
document.addEventListener('DOMContentReady', function popup() {
alert("Hello World")
})
nor this:
<script type="text/javascript">
function popup() {
alert("Hello World")
}
</script>
Not that I really expected it too, but I was getting desperate. If anyone knows what's going on, I'd appreciate any info.
I'm open to this being an issue with hosting this locally on XAMMP but find it doubtful as CSS and HTML are both flying. However the js works if I include it inline with the HTML(?). If it helps, when Firebug displays popup() in the script window it also shows an #conn1source connection.
UPDATE: according to one of the suggestions in the comments if I only write the following in the js file it works:
alert("Hello World")
however the function does not. So I'm guessing this means that I wrapped the function somehow incorrectly in the js file, but I'm following standard practice as far as I am aware.

HTML/Javascript Confusion

I have an extremely basic html document written as the following:
<html>
<head>
<title>A Basic Javascript Game</title>
</head>
<body>
<script language="JavaScript" src="mygame.js">
</script>
</body>
</html>
I've created an according Javascript file, have made sure that it's syntax is alright. The first line of the mygame.js file is:
var persontotalkto = prompt("You wake up one Saturday morning. The Holidays just started, and you can't wait to tell your family where you've decided for all of us to go on vacation! Who do you talk to: WIFE, SON, or DAUGHTER?").toUpperCase();
But when I open the html file, I'm not getting any prompt whatsoever. I have javascript enabled, so what is the problem?
Change the script tag to either the HTML4 version:
<script type="text/javascript" src="mygame.js"></script>
Or the HTML5
<script src="mygame.js"></script>
(Either will work on any browser released this millennium.)
Change
<script language="JavaScript" src="mygame.js">
</script>
to
<script type="text/javascript" src="mygame.js">
</script>

2 versions of jQuery -> 2 documents. why?

I have a small page:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title></title>
<script type="text/javascript" src="jquery-1.4.2.js"></script>
<script type="text/javascript" src="temp.js"></script>
</head>
<body>
<p>foo</p>
<p>bar</p>
</body>
</html>
and I'm trying to load two different versions of jQuery:
// temp.js
jQueryScriptOutputted = false;
initJQuery = function() {
//if the jQuery object isn't available
if (typeof(myjQuery) == 'undefined') {
if (!jQueryScriptOutputted) {
//only output the script once..
jQueryScriptOutputted = true;
//output the script (load it from google api)
document.write("<script type=\"text/javascript\" src=\"jquery-1.6.4.js\"></script>");
document.write("<script type=\"text/javascript\">var myjQuery = $.noConflict(true);</script>");
}
setTimeout("initJQuery()", 50);
} else {
myjQuery(function() {
// Check jQuery versions
console.log('myjQuery version = ' + myjQuery().jquery);
console.log('$ version = ' + $().jquery);
console.log('jQuery version = ' + jQuery().jquery);
// Get the data of the actual poll
document.write("Where is foo and bar?!?");
});
}
}
initJQuery();
but it seems that this loads two different documents. I mean, when you open the page, the paragraphs get lost. How come?!?
Calling document.write after the page has loaded will overwrite the entire page with the document.write parameter. Consider using something else like $().append or $().html to change the markup.
i.e.
myjQuery(function() {
$('body').append("<p>Where is foo and bar?!?</p>");
});
You must only load one version or the other.
In other words, only have one jquery library installed to the page.
The problem is that you are writing the <script> tags to the document and not the <head>
Please see these instructions for full information on how to dynamically load jQuery.
The tutorial explains how to do it really well.
Hope this helps.

Document.links empty after calling document.close

When you execute following example using Firefox 3:
<html>
<head>
<script language="javascript" type="text/javascript">
<!--
function openWindow(){
var w = window.open('', 'otherWin', 'width=600,height=600');
w.document.write(document.getElementsByTagName("html")[0].innerHTML);
w.document.close();
reportLinks(w.document.links);
}
function reportLinks(links){
var report = 'links: '+links.length;
for (var i=0;i<links.length;i++){
report += '\n (link='+links[i].href+')';
}
alert(report);
}
//-->
</script>
</head>
<body>
<p>Open Same Content and Show Links Report</p>
<p>Show Links Report</p>
</body>
</html>
You will see that both the number of links shown when clicking on 'Show Links Report' as when clicking on 'Open Same Content and Show Links Report' will be 2. However when having an external JavaScript file reference from this page the behavior seems different (just make an empty file some.js if you want). When clicking 'Open Same Content and Show Links Report' the number of links will be 0.
<html>
<head>
<script language="javascript" type="text/javascript" src="some.js"></script>
<script language="javascript" type="text/javascript">
<!--
function openWindow(){
var w = window.open('', 'otherWin', 'width=600,height=600');
w.document.write(document.getElementsByTagName("html")[0].innerHTML);
w.document.close();
reportLinks(w.document.links);
}
function reportLinks(links){
var report = 'links: '+links.length;
for (var i=0;i<links.length;i++){
report += '\n (link='+links[i].href+')';
}
alert(report);
}
//-->
</script>
</head>
<body>
<p>Open Same Content and Show Links Report</p>
<p>Show Links Report</p>
</body>
</html>
It is probably a matter of loading the page and the moment that reportLinks executed exactly. I assume that the external some.js is added that the document is not completely build up. Is there a way that I can register this reportLinks call for onload event so that I can be sure that document.links is complete?
By the way the example works fine in both cases with Google Chrome.
(added after answer1)
As suggested by Marcel K. I rewrote the example, added also the code the way I really would like to have the thing going. And now testing it, and this simple example seems to work with Firefox and with Chrome.
<html>
<head>
<script type="text/javascript" src="some.js"></script>
<script type="text/javascript">
<!--
function openWindow(){
var w = window.open('', 'otherWin', 'width=600,height=600');
w.document.write('<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">\n<html>\n'+
document.getElementsByTagName("html")[0].innerHTML+'\n</html>');
w.onload=function(){
reportLinks(w.document.links);
};
w.document.close();
}
function reportLinks(links){
var report = 'links: '+links.length;
for (var i=0;i<links.length;i++){
report += '\n (link='+links[i].href+')';
}
alert(report);
}
//-->
</script>
</head>
<body>
<p>Open Same Content and Show Links Report</p>
<p>Show Links Report</p>
</body>
</html>
I had hoped with this simple example to show a simple case of the actual code I am writing. A print preview screen of complicated html in which I want to disable all hrefs once opened. But in that one the onload handler is never called... How can I register an onload handler in this case in the most robust way?
Many thanks,
Marcel
As I said in a comment, this is a very strange issue. But I think it happens because the inclusion of an external script causes a delay in page rendering (of the new page) and its DOM might not be ready to inspect.
My suspicion is supported by the fact that adding the (new) defer attribute seems to solve this issue:
This Boolean attribute is set to indicate to a browser that the script is meant to be executed after the document has been parsed.
The defer attribute can be set on the original page, as you want an exact copy of it. You can set it if it doesn't matter where a script is being included (e.g., when using document.write in your included file it does matter at which place you include it).
As defer is a Boolean attribute, it is activated when it is simply present (defer) or (when using XHTML) set to itself (defer="defer"). In your case, the script inclusion would read:
<script type="text/javascript" src="some.js" defer></script>
Update regarding your update: you should still insert a Doctype in the main page (consider using the HTML 5 one).
And I think the way you attached your onload event is the best you can do.
But considering the goal you want to achieve (a print preview without hyperlinks): you can also use the "print" media attribute and style hyperlinks like text; that's way more easy than the thing you are doing and it works when JavaScript is disabled.
The only way I could make the example above work portable over Firefox, Chrome and IE is by registering the onload listener through inlined JavaScript in the HTML loaded in the popup window. Following example code shows how.
<html>
<head>
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<p>Open Same Content and Show Links Report</p>
<p>Show Links Report</p>
</body>
</html>
This page uses a script in script.js file. Following shows the content of that file.
function openWindow(){
var w = window.open('', 'otherWin', 'width=600,height=600');
w.document.write(
'<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">\n<html>\n'+
document.getElementsByTagName("html")[0].innerHTML+
'\n <script type="text/javascript">\n'+
' function addOnloadListener(listener){\n'+
' if (window.addEventListener) {\n'+
' window.addEventListener("load", listener, false);\n'+
' } else {\n'+
' window.attachEvent("onload",listener);\n'+
' }\n'+
' }\n'+
' addOnloadListener(function(){reportLinks(document.links);});\n'+
' </script>\n'+
'</html>');
w.document.close();
}
function reportLinks(links){
var report = 'links: '+links.length;
for (var i=0;i<links.length;i++){
report += '\n (link='+links[i].href+')';
}
alert(report);
}
When putting the function addOnloadListener directly in the JavaScript file (not inlined in the page) it doesn't work in IE6 because, I believe, it cannot handle the order of script entries correctly. When addOnloadListener was not inlined the inlined call to addOnloadListener didn't work, it simply couldn't find the function in the earlier:
<script type="text/javascript" src="script.js"></script>
The code is only a simple example that doesn't really do a lot. I used it for disabling all links in a print preview popup page.
A simpler way to register an onload listener for a popup window portable over browser is always welcome.
Thanks,
Marcel

Categories