Updating automatically an HTML content when the imported *.json values are changed - html

I have an HTML code that imports a LOCAL but UPDATABLE *.json content, and it must be updated automatically when the *.json file is updated.
This is the *.HTML code:
<html>
<head>
<script type="text/javascript" src="sample.json"></script>
<script type="text/javascript" >
function load() {
setInterval(function () {
var mydata = JSON.parse(data);
var div = document.getElementById('data');
div.innerHTML = mydata[0].location.altitude;
}, 100);}
</script>
</head>
<body onload="load()">
<div id="data">
</div>
</body>
</html>
and the adapted sample.json file is:
data = '[{"location": {"altitude": 40}}]';
I just wanna see the altitude is changing in the browser(HTML) whenever the sample.json file is updated.
Now the HTML works but only ONCE, I wanna make it dynamic.
What should I do to make the function setInterval work correctly? or maybe this function works only for local changes, not external ones.
Thnks, Sadeq

If you want the browser to get data from a URL even interval, then you need to write code which gets data from a URL in the interval. e.g. with the Fetch API. (At which point you should make it JSON instead of JS).
However HTTP is not fast. You do not want to be polling over HTTP every 100ms. Consider using Websockets to push the data from the server when it changes instead of polling.

Related

use an include to include an html file that contains a script

I am working on a Google Apps Script. My situation is that I have an index.html file and a few others which should all share a menu on the side.
I therefore have a function as follows
function include(File) {
return HtmlService.createHtmlOutputFromFile(File).getContent();
};
and use
<?!= include('leftMenu'); ?>
to include that in my html files.
The problem I have is that in the included file there is a function called that is defined in my Code.gs
<div class="leftmenu">
Main menu<br>
<?var url = getScriptUrl();?><a href='<?=url?>?page=newInvoice'>New invoice</a><br>
<?var url = getScriptUrl();?><a href='<?=url?>?page=index'>Home</a>
</div>
This function works as I would expect as long as these lines are in the "main" html file but they produce text if they are in the "included" html file.
I hope that makes sense and some one is kind enough to explain what the problem is and hopefully how I can get round it.
Thank you
Neill
14 Dec. 2016 edited to try and explain exactly what my problem is
I have a html file named “newinvoice.html”.
This has javascript functions in it as follows
<script type="text/javascript">
function formSubmit() {
google.script.run.withSuccessHandler(updateUrl).onSubmitButton(document.forms[0]);
}
function updateUrl(url) {
var successMsg = document.getElementById('output');
successMsg.innerHTML = 'New invoice created, saved and sent per Email';
}
</script>
I can move these functions into a separate html file as you suggested. This is called menu_JS.html and is included in my main file with
This works perfectly.
I have a call to one of these these functions - also in the main html “newinvoice.html” This is as follows
<div class="leftmenu">
Main menu<br>
<?var url = getScriptUrl();?><a href='<?=url?>?page=newInvoice'>New invoice</a><br>
<?var url = getScriptUrl();?><a href='<?=url?>?page=index'>Home</a>
</div>
If I move this into a separate file “leftMenu.html” and include that in “newinvoce.html” with
Then the output no longer works.
It appears that the scripts are trying to run before the files are included instead of the include and then the execution as I am used to from PHP.
As always, I appreciate anyone willing to take the time to help me. This is frustrating. Thank you!
Create another HTML file and put the script you want to run client side in that file. Then use the same include statement to include that file.
So make menu_JS.html and place your functions in that, between script tags:
<script>
firstFunction(){
alert("In the first function");
}
secondFunction(){
alert("In the second function");
}
</script>
And in your main HTML template file, preferable after the body loads, place:
<?!= include('menu_JS'); ?>
NOTE that the script is in an HTML file and NOT a Script file.
EDIT: Nov 15 2016
Below is the variation of the function which I have that is working for my needs. Note that I am evaluating the included html file. I had previously used code more similar to your (commented out) and changed it to this some time ago:
function include(filename) {
// return HtmlService.createHtmlOutputFromFile(filename)
return HtmlService.createTemplateFromFile(filename).evaluate()
.getContent();
}
//function includeRaw(filename) {
// return HtmlService.createTemplateFromFile(filename).getRawContent();
//}
And this is how I load the initial html file. This is often in the doGet() function, but may be elsewhere
var result=HtmlService.createTemplateFromFile('GridView').evaluate()
.setTitle('Boxwood Registrations')
.setWidth(1285)
.setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL);
return result;

populating a DataTable with a JSON file directly, or querying a local spreadsheet (google visualization)

I am looking for the easiest way to populate a data table in google visualizations using either a json file or a local spreadsheet(.xlsx).
heres my code:
<!DOCTYPE html>
<html>
<head>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable.fromJSON(sampleData.json,0.6);
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, {width: 400, height: 240});
}
</script>
</head>
<body>
<!--Div that will hold the pie chart-->
<div id="chart_div"></div>
</body>
</html>
Heres my json file:
{
"cols": [
{"id":"","label":"Topping","pattern":"","type":"string"},
{"id":"","label":"Slices","pattern":"","type":"number"}
],
"rows": [
{"c":[{"v":"Mushrooms","f":null},{"v":3,"f":null}]},
{"c":[{"v":"Onions","f":null},{"v":1,"f":null}]},
{"c":[{"v":"Olives","f":null},{"v":1,"f":null}]},
{"c":[{"v":"Zucchini","f":null},{"v":1,"f":null}]},
{"c":[{"v":"Pepperoni","f":null},{"v":2,"f":null}]}
]
}
When I run my code in my browser, I get
"Uncaught ReferenceError: sampleData is not defined"
Anyone know how I can make this work?
Thanks in advance
You COULD simply place the contents of your JSON file right inline there in your HTML where the string "sampleData.JSON" is. That is, take out "sampleData.JSON" and replace it with the entire contents of your JSON file. I'm pretty sure you'll make some progress if you do this.
Try putting sampleData.json in quotes, assuming that the filename is sampleData.json and is in the same folder as your HTML.
var data = new google.visualization.DataTable.fromJSON('sampleData.json',0.6);

refresh data read from text file with out page refresh

i am a novice at Java and JS so this will be very basic.
I've got this code that creates a text file in a specific directory. i only got as far as creating an actuale file, however, as the text file will be frequantely updated, i need the page to refresh/reload the text file and display it's data (just in the blank page). How do i do this, with out user needed to click refresh (auto refresh in sense, however, i've tried auto refresh and it does not seem to reload JS and/or display text file's content)
Create Text file/Read/Display content/Refresh and/or Reload - no user refresh
<script>
function createFile()
{
var object = new ActiveXObject("Scripting.FileSystemObject");
var file = object.CreateTextFile("C:/Documents and Settings/galimbek.sagidenov/My Documents/Practice HTML_Photoshop_java/BroadcastTest.txt", false);
file.WriteLine('Hello World');
file.WriteLine('Hope is a thing with feathers, that perches on the soul.');
file.Close();
}
</script>
this will not accomplished by using client side javascript only you have to use server side code:
server ex (using node.js):
server :
var http = require("http"),
fs=require("fs");
http.createServer(function(request, response) {
fs.writeFileSync("C:/Documents and Settings/galimbek.sagidenov/My Documents/Practice HTML_Photoshop_java/BroadcastTest.txt", 'Hello World\r\nHope is a thing with feathers, that perches on the soul.');
}).listen(8888);
client
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
$(function(){
$.get("http://localhost:8888",function(){
console.log("writing to file successeded");
})
})
</script>

How to send json string from backing bean to external javascript file?

i have external javascript file for drawing google charts
and in this js file i want to access backing bean to get json string.
js file:
window.onload = function(){
if(typeof(google)!= undefined){
google.load('visualization', '1.0', {'packages':['corechart'],callback: drawChart});
}
};
function drawChart() {
var jsonStr=#{myBean.jsonStr} // i want to be able to do something like that
var data_recSent = new google.visualization.DataTable(jsonStr);
//
//
}
if there's no possible solution/workaround for this case, please advise about other solutions.
best solution i have found so far, is to store the json string in hidden input, and then get the value of this hidden input in the js file.
If the result of #{myBean.jsonStr} is big, I would suggest you to make it cached by browser as follows:
Use a separated js file to keep this json:
myjson.js
var jsonStrGobal=JSON_PLACEHOLDER;
In the html header
<script language="javascript" type="text/javascript" src="myjson.js?version=#{myBean.jsonVersion}" />
myjson.js is not stored physically, but loaded by a servlet or a backing bean, JSON_PLACEHOLDER is replaced by your json, this servlet of backing bean will set the Cache-control on http response header to make browser cache it. Servlet can be registered in web.xml, backing bean can be declared in pages.xml as a page action.
Increase myBean.jsonVersion whenever the content of json changes so that browser gets notified.

JSON and passing a URL value as a parameter - Chrome Extension

Ok, this is my final tango with this. Below I've listed the code. I'm able to get the value of the url and display it on screen for the current (active tab) in Google Chrome. Now all I have to do is pass that value as a parameter in the URL via JSON. My processing file resides on a our remote server - in php. Everything I've done with respect to this has worked to perfection. However, any attempts to pass the current url or any url as one of the parameters - e.g. ?format=json&url=http://something.com&callback=? - results in nothing. I'm not sure if what I'm doing is wrong or if it is even possible. The important thing to note is that all we are looking to do is pass the url to a remote server for storage, processing etc and send back results. I have everything working but I just can't seem to get the url to pass as a parameter.
<html>
<head>
<title>API JSON Test</title>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<script>
window.addEventListener("load", windowLoaded, false);
function windowLoaded() {
chrome.tabs.getSelected(null, function(tab) {
document.getElementById('currentLink').innerHTML = tab.url;
});
}
</script>
<script type="text/javascript">
$(document).ready(function(){
var timeService =
"http://api.ulore.com/api2.php?key=abce&url="+tab.url+"&format=json&callback=?";
$.getJSON(timeService, function(data) {
$('#showdata').html("<p>url_results="+data.post.url+"</p>");
});
});
</script>
<div id="showdata"></div>
</head>
<body>
</body>
</html>
Again, all the JSON works fine when I'm testing other code. Even if I put in a NON-URL value as a parameter for url=..... it throws the appropriate error. However, it will not accept a URL for some reason.
Any feedback will be greatly appreciated.
Thanks,
Ethan-Anthony
Try encoding and decoding the url.
http://www.w3schools.com/tags/ref_urlencode.asp
http://php.net/manual/en/function.rawurlencode.php
http://phpjs.org/functions/rawurlencode:501