Embedding JS and HTML at the same time fails - javascript

I would like to have many HTML pages of one type, the only difference being the page title and some data stored in different .json files. Everything else should be stored in two centralized files, a .js and an .html file. In pseudocode the pages should look like this:
<html>
<head>
include global_script.js
include specific_data_n.json
</head>
<body>
include global_body.html
</body>
</html>
where the n-th page includes the data file specific_data_n.json but everything else is always the same.
I know how to include .js and .json files in the header. However, I don't really know how to include the .html file in the body. I searched on the net and, in particular, found this question: Server side includes alternative I tried different ways of including the body proposed in the answers but whatever I tried, I got a JS error.
Here is a minimal example of the problem. First, the working file where the body is in the main file and not in an extra file:
function init(){document.getElementById('demo').innerHTML = '2+2=4';}
<!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" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /><head>
<script language="javascript" type="text/javascript" src="minimal.js"></script>
</head>
<body onload="init();">
<div id="demo">
2+2=5
</div>
</body>
</html>
Now I tried to put the body in an external file following one of the answers of the question linked above.
<!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" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script language="javascript" type="text/javascript" src="minimal.js"></script>
</head>
<body onload="init();">
<!-- Content, inclusion from https://stackoverflow.com/questions/35249827/can-you-link-to-an-html-file -->
<div w3-include-html="body_minimal.html"></div>
<script>
(function () {
myHTMLInclude();
function myHTMLInclude() {
var z, i, a, file, xhttp;
z = document.getElementsByTagName("*");
for (i = 0; i < z.length; i++) {
if (z[i].getAttribute("w3-include-html")) {
a = z[i].cloneNode(false);
file = z[i].getAttribute("w3-include-html");
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
a.removeAttribute("w3-include-html");
a.innerHTML = xhttp.responseText;
z[i].parentNode.replaceChild(a, z[i]);
myHTMLInclude();
}
}
xhttp.open("GET", file, true);
xhttp.send();
return;
}
}
}
})();
</script>
</body>
</html>
and the body_minimal.html which is included:
<div id="demo">
2+2=5
</div>
I also tried different further approaches for embedding the body_minimal.html file (which I can present if needed) but none of them works, so I assume that it is some fundamental problem. I always get the error in the JS debugger:
TypeError: document.getElementById(...) is null
I need to add that I have no experience neither in HTML nor in CSS and am mostly copy&pasting stuff from different tutorials, forums and Q&A sites so I do not really understand what this code for the embedding of the HTML file is doing. :)
Thanks for any hint on what the problem might be and a happy new year!

This really belongs as a comment but unfortunately my account is new so I'm not allowed...An answer will have to do.
If your webhost runs PHP I'd suggest looking into PHP includes, they're much simpler.
Basically, you would save your central html file as a .php file instead and include the HTML file you want using
<?php
include 'global_body.html';
?>

Found a solution which looks stupid, but as you know, if something looks stupid but works, it isn't stupid. :) I just made another .js file which writes the body contents via document.write():
<!DOCTYPE html>
<html>
<head>
<script language="javascript" type="text/javascript" src="script.js"></script>
</head>
<body>
<script language="javascript" type="text/javascript" src="body.js"></script>
</body>
</html>
And the included .js files:
//body.js
document.write('<div id="demo"->2+2=5</div>');
and
//script.js
document.getElementById('demo').innerHTML = '2+2=4';
The only problem is that in a real world scenario the contents of the body are many lines and JS needs a backslash on each line break. Also, the syntax highlighting only shows all the HTML code in one colour as from JS's point of view it is just a string. Therefore I'm still interested in better/cleaner solutions!

Related

jquery script not working inside HTML

( Answered: dont use <script type="text/javascript" src="jquery-1.8.0.min.js"></script> in html)
I am learning Jquery from this tutorial :
http://www.littlewebhut.com/javascript/getting_started/
I created One Html , 1 js file . put them on same physical folder ,put "jquery-1.8.0.min.js" in same folder , put a link of js file in html page
But it is not working .
my HTML:
<!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" lang="en" xml:lang="en">
<head>
<title>Demo</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
</head>
<body>
<h1>Heading one</h1>
<p>This is just some text for heading 1</p>
<script type="text/javascript" src="jquery-1.8.0.min.js"></script>
<script type="text/javascript" src="my_code.js"></script>
</body>
</html>
My Jquery Page (my_code.js) :
$(document).ready(function(){
$("p").hide();
$("h1").click(function(){
$(this).next().slideToggle(300);
});
});
there is some minor mistake that is happening ,
I tried to search , but could not found relevant link .PLease suggest if I am missing something
Your code is working fine.There must be some problem with your jquery file path. Try including CDN hosted jquery library as follows or check your path:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
I have tried this on js fiddle and it's working fine I guess this is what you want ,right when on clicking the h1 tag you need that p to hide if I am not wrong ,
This is the js fiddle http://jsfiddle.net/Saranshshrma/7rzLW/1/
If this script is, small you can always put in, this
<script></script>
Tags before body content but remember put your Jquery before anything else any script or code you want to execute and you can post the chrome inspect element errors while executing this code
What error are you getting ? See the console/dev tools (f12) and notice you have to click the header text to trigger the effect:
http://jsfiddle.net/m5LL4/
$(document).ready(function(){
$("p").hide();
$("h1").click(function(){
$(this).next().slideToggle(300);
});
});
I did paste your code, just take a part of the html with the same jquery version and it works.
Is javascript enabled in your browser?
If you are using chrome Go Ctrl+H click on Setting in left side->show advanced Setting->Privacy->Content Settings->Allow all sites to run Javascript.
If already checked check for your jquery path file name.

how can I get text strings from list in txt document?

how would I do if I wanted to have an div on my site that contained a text and I wanted to replace that text every 5sec with a new text string that It got from an list from an external text file.
So something like this but in the "textlist" div it puts the first sting from the text file then 5 sec after it replaces that with the text from the second row, and so on.
CODE:
<!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=utf-8" />
<title>test_text</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
function run() {
document.getElementById("textlist").innerHTML = "The sting from the text file";
}
window.setInterval(run,5000);
</script>
</head>
<body>
<div id="textlist">the text</div>
</body>
</html>
and the text file would be like this for example:
/mytextfile.txt
(content in the file)
01: The tips 1
02: The tips 2
03: The tips 3
04: The tips 4
05: The tips 5
06: The tips 6
Thanks in advance hopes it make sense.
I'd do that a little differently:
<!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=utf-8" />
<title>test_text</title>
</head>
<body>
<div id="textlist">the text</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
var ajax = $.ajax({
url: 'the url to the text list',
type: 'GET'
});
ajax.done(function (data) {
var list = $.trim(data).split(/\n+/), index = 0;
function run() {
if (index >= list.length) {
index = 0;
}
$('#textlist').html(list[index]);
index ++;
}
window.setInterval(run, 5000);
});
});
</script>
</body>
</html>
So in this example, we first move all of the scripts to the bottom of the body. That way we can be sure that our html has been rendered before the scripts run.
Secondly, we put our custom JavaScript into a jQuery docready. This way we are being extra safe that the page is fully interactive before our scripts try to run.
The next thing we do is use ajax to fetch the text file. Due to same-origin policy, this will only work if that file resides on the same server that is serving the web page.
After that, we attach a handler to the ajax promise. In other words, when the ajax request is "done", it will run a function and pass in the data that was retrieved. We turn the data into a list by trimming white space off the string and splitting it wherever there are new lines. We also set up a variable to track our place in the list.
The run function will check to see what place we are at in the list. If we've gone farther than the amount of items in the list, we'll reset it to 0. Then we'll replace the html of our element with the current list item. Finally we move up one place in the list.
Lastly we call setInterval so that run will run once every 5 seconds.
Caveat: I haven't tested this but conceptually it will work. There may be a typo or perhaps some specific ajax requirements I'm not aware of having to do with your server but the process I've described should work.
you can use ajax for that.with jquery (that is already attached to your document) you can easily do that as follow:
<!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=utf-8" />
<title>test_text</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
var lines="";
$.get( "your_text_file_path", function( data ) {
lines=data.split("\n");
});
var i=0;
window.setInterval(function (){
if(i<=lines.length){
$("#textlist").html(lines[i]);
i++;
}else{
i=0;
}
},5000);
</script>
</head>
<body>
<div id="textlist">the text</div>
</body>
</html>
here you are a demo does that

sample HTML to test javascript codes

I have just started learning Javascript and Ok here is a code I want to try and see it in the browser, so I create a test.js file and put this in it:
function useless(callback) {
return callback
}
var text = 'Amigo';
assert(
useless(function(){ return text; }) === text,
"The useless function works! " + text);
But still there is more, I should write a minimum HTML page than can call this function, What is sample HTML to host this method in it?
I have written something like this but still there is something wrong with it:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<script src="hehe.js" >
useless('Amigo');
window.onload=useless('Amigo')
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<script type="text/javascript" src="hehe.js"></script>
<script >
useless('Amigo');
window.onload=useless('Amigo')
</script>
</body>
</html>
You can load the source in a separate script from the inline one that you call it in. Note that this assumes that hehe.js is in the root directory of your site.
For testing js in general jsFiddle is a nice resource that lets you define your html/js/css and experiment with small changes without having to write out all the files.

Global variables in Javascript across multiple files

A bunch of my JavaScript code is in an external file called helpers.js. Inside the HTML that calls this JavaScript code I find myself in need of knowing if a certain function from helpers.js has been called.
I have attempted to create a global variable by defining:
var myFunctionTag = true;
In global scope both in my HTML code and in helpers.js.
Heres what my html code looks like:
<html>
...
<script type='text/javascript' src='js/helpers.js'></script>
...
<script>
var myFunctionTag = false;
...
//I try to use myFunctionTag here but it is always false, even though it has been se t to 'true' in helpers.js
</script>
Is what I am trying to do even feasible?
You need to declare the variable before you include the helpers.js file. Simply create a script tag above the include for helpers.js and define it there.
<script type='text/javascript' >
var myFunctionTag = false;
</script>
<script type='text/javascript' src='js/helpers.js'></script>
...
<script type='text/javascript' >
// rest of your code, which may depend on helpers.js
</script>
The variable can be declared in the .js file and simply referenced in the HTML file.
My version of helpers.js:
var myFunctionWasCalled = false;
function doFoo()
{
if (!myFunctionWasCalled) {
alert("doFoo called for the very first time!");
myFunctionWasCalled = true;
}
else {
alert("doFoo called again");
}
}
And a page to test it:
<html>
<head>
<title>Test Page</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<script type="text/javascript" src="helpers.js"></script>
</head>
<body>
<p>myFunctionWasCalled is
<script type="text/javascript">document.write(myFunctionWasCalled);</script>
</p>
<script type="text/javascript">doFoo();</script>
<p>Some stuff in between</p>
<script type="text/javascript">doFoo();</script>
<p>myFunctionWasCalled is
<script type="text/javascript">document.write(myFunctionWasCalled);</script>
</p>
</body>
</html>
You'll see the test alert() will display two different things, and the value written to the page will be different the second time.
OK, guys, here's my little test too. I had a similar problem, so I decided to test out 3 situations:
One HTML file, one external JS file... does it work at all - can functions communicate via a global var?
Two HTML files, one external JS file, one browser, two tabs: will they interfere via the global var?
One HTML file, open by 2 browsers, will it work and will they interfere?
All the results were as expected.
It works. Functions f1() and f2() communicate via global var (var is in the external JS file, not in HTML file).
They do not interfere. Apparently distinct copies of JS file have been made for each browser tab, each HTML page.
All works independently, as expected.
Instead of browsing tutorials, I found it easier to try it out, so I did. My conclusion: whenever you include an external JS file in your HTML page, the contents of the external JS gets "copy/pasted" into your HTML page before the page is rendered. Or into your PHP page if you will. Please correct me if I'm wrong here. Thanx.
My example files follow:
EXTERNAL JS:
var global = 0;
function f1()
{
alert('fired: f1');
global = 1;
alert('global changed to 1');
}
function f2()
{
alert('fired f2');
alert('value of global: '+global);
}
HTML 1:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script type="text/javascript" src="external.js"></script>
<title>External JS Globals - index.php</title>
</head>
<body>
<button type="button" id="button1" onclick="f1();"> fire f1 </button>
<br />
<button type="button" id="button2" onclick="f2();"> fire f2 </button>
<br />
</body>
</html>
HTML 2
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script type="text/javascript" src="external.js"></script>
<title>External JS Globals - index2.php</title>
</head>
<body>
<button type="button" id="button1" onclick="f1();"> fire f1 </button>
<br />
<button type="button" id="button2" onclick="f2();"> fire f2 </button>
<br />
</body>
</html>
Hi to pass values from one js file to another js file we can use Local storage concept
<body>
<script src="two.js"></script>
<script src="three.js"></script>
<button onclick="myFunction()">Click me</button>
<p id="demo"></p>
</body>
Two.js file
function myFunction() {
var test =localStorage.name;
alert(test);
}
Three.js File
localStorage.name = 1;
//Javascript file 1
localStorage.setItem('Data',10);
//Javascript file 2
var number=localStorage.getItem('Data');
Don't forget to link your JS files in html :)
If you're using node:
Create file to declare value, say it's called values.js:
export let someValues = {
value1: 0
}
Then just import it as needed at the top of each file it's used in (e.g., file.js):
import { someValues } from './values'
console.log(someValues);
I think you should be using "local storage" rather than global variables.
If you are concerned that "local storage" may not be supported in very old browsers, consider using an existing plug-in which checks the availability of "local storage" and uses other methods if it isn't available.
I used http://www.jstorage.info/ and I'm happy with it so far.
You can make a json object like:
globalVariable={example_attribute:"SomeValue"};
in fileA.js
And access it from fileB.js like:
globalVariable.example_attribute
You can set
window['yourVariableName'] = yourVariable;
and it will make that variable global for all the files.

Time refreshment in the HTML via AJAX

I have one html page with links of chart whenever i refresh HTML paget the chart refreshs.
I heard from my friend that with the help of AJAX that chart will refresh automatically with given time interval without refreshing that html page.
please help me with the html code for the same.
Regards,
Raj
You could use the setInterval() method in javascript, along with a simple framework like jQuery for the AJAX.
It would look something like this:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-us" lang="en-us">
<head>
<title>My AJAX Chart</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
setInterval("refreshChart", 5000); // Refresh every 5 seconds
});
function refreshChart() {
$.get("myChart.php", function(data) {
$("div.chartHolder").html(data);
});
}
</script>
</head>
<body>
<h1>My Chart</h1>
<div class="chartHolder"></div>
</body>
</html>
Since it sounds like you are new to JavaScript, I would recommend you take a look at the jQuery libraries, it can do what you want with a minimal of complication:
Something like this would work:
function updateChart() {
$('#someTable tbody').load('updateChart.html');
}
$(function() {
setInterval(updateChart, 20000);
});
If you combine something like e.g. this; http://ra-ajax.org/Docs.aspx?class=Ra.Extensions.Widgets.Timer with this; http://ra-ajax.org/samples/Chart-Sample.aspx you'll easy get there.
Above samples are for .Net, but there exists similar constructs (and frameworks) also for other other platforms...

Categories