There are two files: 1)app.js and 2) browser.html. app.js just stores a value in a node-js local storage and browser.html should alerts that. But browser.html alerts "null".
My JavaScript code:
var LocalStorage = require('node-localstorage').LocalStorage;
localStorage = new LocalStorage('./scratch');
var a="salam";
global.a=a;
localStorage.setItem('a',a);
My html code:
<!DOCTYPE html>
<html lang="en">
<head>
<title>TEST</title>
</head>
<body>
<input value="Smart contract data" max="25" id="12"></input>
<script src='js/app.js'> </script>
<script>
alert(localStorage.getItem('a'));
</script>
</body>
</html>
What is the problem and its solution? Is there any way to communicate between node-js storage and a html file? Please guide a beginner man.
The issue here is that node-localstorage is entirely backend, and htlm5 localStorage is entirely client side. You will not be able to pull backend values set with node-localstorage on the client end.
In order to pass values from node to the client you will need a template engine. Express provides a pretty complete list of those engines here:
https://expressjs.com/en/resources/template-engines.html
Related
I have an argument in JS which holds pretty much the data. It's the server information to my server. It changes often, e.g 20/64 or 32/64. You get the point.
I am trying to get the contents of the data to go on an external site, however, when I try, it doesn't work.
To summerise, I have a div which holds the data, I want to get that data using JS and put it on an external site which isn't using the same domain or web server.
HTML FILE:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<script src="jquery.js" type="text/javascript"></script>
</head>
<body>
<div id="serverstats-wrapper"></div>
<script src="import.js"></script>
</body>
JS File:
$(document).ready(function(){
$.post("query.php", {},
function (data) {
$('#serverstats-wrapper').html (data);
});
});
var the_main = document.getElementById("serverstats-wrapper");
var the_data = the_main.textContent ? the_main.textContent : the_main.innerText;
I want to get the text from the html file to the js file then take it to an external website.
Tasid! This won't work! JS does't have such a technique implementet. To do so, you need node.js. This allows you to send the data over a socket to your other webserver.
It does't work difrently, because JS is executed direct on your PC.
You can grab data from another site; but you cannot inject JS code into another site. Here are some methods to retrieve html from another site: Include another HTML file in a HTML file
I'm trying to take input from a form and save it into a text file that is in the same folder as the html file. This is what I have so far:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Reservation</title>
<meta name="description" content="The HTML5 Herald">
<meta name="author" content="SitePoint">
<link rel="stylesheet" href="css/styles.css?v=1.0">
<script>
function writeToFile(item, name, time)
{
alert("Hello " + item);
var fso = new ActiveXObject("Scripting.FileSystemObject");
var fh = fso.OpenTextFile("E:/labChart/etc/reserve.text", 8);
fh.WriteLine(item);
fh.Close();
}
function readFile()
{
var fso = new ActiveXObject("Scripting.FileSystemObject");
var fh = fso.OpenTextFile("reserve.text", 1, false, 0);
var lines = "";
while (!fh.AtEndOfStream) {
lines += fh.ReadLine() + "\r";
}
fh.Close();
return lines;
}
</script>
</head>
<body>
Reservation
<br>
<form>
Item:
<br>
<input type="text" name="item" id="item">
<br>
Name:
<br>
<input type="text" name="name" id="name">
<br>
Time:
<br>
<input type="date" name="time" id="time">
<br>
<br>
<input type="submit" value="Submit" onclick="writeToFile(document.getElementById('item').value, document.getElementById('name').value, document.getElementById('time').value)">
</form>
<script src="js/scripts.js"></script>
</body>
</html>
This does take the info from "item" and pass it to the function writeToFile() because the test alert does work. But whenever I check the file reserve.text nothing is written there. I'm very new to javascript and most of this is an amalgamation of code I saw other people using online for similar effects. Does anyone know why it is not working? Am I writing the path incorrectly? Am I not writing the script correctly?
The problem with this is simple: Lets say a developper created javascript code to go through all your filesystem and populate it with dummy files, ruining your hard drive in the process? That is why javascript won't allow you to do this kind of operation. When we want to save information, usually, its done using server-side code and not the client's computer (unless of course we are talking about things like cookies).
The point of my answer is to let you rethink who does the saving and to where. It should be up to the server to save and retain any information for a user, and so you would not write this kind of javascript code... It is best to save data somewhere your client cannot control or edit, like on the server for instance.
I could suggest some easy PHP code, and instead of storing inside a text file, try a database... PHP is a server-side language which will let you save things to files on your server computer, however your server must be able to run PHP, most computers don't come built in with the PHP language and so you will also need a webserver with php built-in..
In my opinion your entire approach is bad; you need to learn PHP and mySQL to store and load persistent data.
- Edit: accessing the file system from JavaScript is a huge security risk and therefore not allowed in general. Unless your goal is specifically to write files from JS, there are better alternatives.
Anyway, this code will only work on Internet Explorer, and only with the security settings way down. You shouldn't pursue this though.
If your end goal is to write a web app that stores and displays reservations, get XAMPP and find a beginner PHP + database tutorial.
When I have a variable defined into server context, sometimes I need use it into javascript context; for example the session id.
What's the better way to do it?
I want to separate javascript files and view files (in my case jsp); for the moment I have found 2 ways:
1) myVariables.js.jsp: create a jsp file that returns javascript code
myLib = {
sessionID: "${sessionId}",
[...]
}
and import it as javascript into the jsp view file:
<html>
<head>
<script src="myVariables.js.jsp"></script>
[...]
</head>
<body>
[...]
</body>
</html>
I'm able to get the session id writing: myLib.sessionId.
Pros: handy and rapid.
Cons: write a jsp file that acts as js.
2) Save the server variable into hidden input fields (for example, in the main part of the template):
<html>
<head>
<script src="myLib.js"></script>
[...]
</head>
<body>
<form id="myVariables">
<input type="hidden" name="sessionId" value="${sessionId}" />
[...]
</form>
[...]
</body>
</html>
I'm able to get the session id writing a specific function into myLib.js library:
myLib = {
sessionId: function() {
return $("form#myVariables > input[name=sessionId]").val();
},
[...]
}
Pros: javascript and view completely separated.
Cons: more code to write; little harder to understand than the previous.
In my opinion first way is better because your pages will be clean and more readable. That'is very important! ;)
Best regards
There's a third way that I think takes the best of both of your suggestions: An inline script tag containing the variables:
<html>
<head>
<script>
var myLib = {
sessionID: "${sessionId}",
[...]
};
</script>
</head>
<body>
[...]
</body>
</html>
No separate JSP to write. Just as separated as the second solution in your question, as the JavaScript is tied just to the myLib, exactly as the JavaScript in your second solution is tied to the structure of the form.
There's a benefit to your first solution we should call out: It allows the HTML to be cached by the browser (by separating the variables into a separate request, e.g., for the .js.jsp). Combining the variables with the HTML (either as above, or the second approach in your question) means the HTML has to be served with caching diminished or disabled.
Goal:
To sum it up, I'm trying to replace an excel spreadsheet. I'm creating an application that will run in IE9, but does not connect to the internet or an intranet (I know, I know. Just bear with me. If you're curious read more below). It needs to use CRUD (create, read, update, and delete) methods on a set of data that changes daily. The dataset must persist even when the browser is closed.
Question:
What options are available, using javascript and html, for storing data on the local computer the web page is accessed on? I'm doing this at work, so there will be no server-side to this. I also will not be able to install any software on the computer, although I can download javascript plugins. The webpage will be loaded from a file on the computer, using Win 7 and IE9.
Background:
This deserves an explanation. I use an excel spreadsheet to track a set of data that changes daily. I'm learning HTML and javascript, and I can create a much better (and easier to use) solution as a webpage. I can create the UI / UX, but I'm having a difficult time figuring out how to store the data on the local computer. Any good suggestions?
Attempts:
Unfortunately, it seems localStorage is not an option. I'm attempting to use jStorage, but I've been running into problems there, also. A similar set of problems has been encountered using simpleStorage.
Thank you for considering, please let me know if any more info is needed, or if I need to clarify something.
Addendum:
Localstorage, and other forms of HTML5 storage, do not work. Officially it does, unofficially it is very buggy. See blog post here, and SO answer here. Either way, with the following simple code:
HTML:
<!DOCTYPE html>
<html>
<head>
<title>Backlog Tracker</title>
<script src="jquery-2.1.1.min.js"></script>
<script src="backlog_localstorage.js"></script>
</head>
<body>
</body>
</html>
and javascript (ref as "backlog_localstorage.js" above):
$(document).ready(function(){
$("body").append("<button>Try It</button>");
$("button").click(function(){
localStorage.setItem("key1", "Hello");
console.log(localStorage.getItem("key1"));
});
});
... I get the following error: "SCRIPT5007: Unable to get value of the property 'setItem': object is null or undefined" on the line localStorage.setItem("key1", "Hello");
HTA (which is really just an html file with one extra tag and a different file extension) is one possible solution for windows users:
Important: Save as demo.hta to run on windows as an app
<!DOCTYPE html>
<html> <!-- some parts lifted from
http://msdn.microsoft.com/en-us/library/ms536496(v=vs.85).aspx
http://msdn.microsoft.com/en-us/library/ms536473(v=vs.85).aspx
-->
<head>
<title>State Saving Demo</title>
<hta:application id="App"
application="yes"
applicationname="demo"
icon="calc.exe"
border="thin"
caption="yes"
sysmenu="yes"
showintaskbar="yes"
singleinstance="yes"
sysmenu="no"
maximizeButton="yes"
minimizeButton="yes"
navigable="no"
scroll="yes"
contextmenu="no"
selection="no"
windowstate="normal" >
<!-- Use Internet Explorer 10 Standards mode (to use JSON, CSS3, etc...) -->
<meta http-equiv="x-ua-compatible" content="IE=10">
</head>
<body onload=loadMe() >
<h1 id=h1>Command-line args: </h1>
<h3>Persisted Text</h3>
<textarea rows=20 cols=100 id=mydata onchange=saveMe() >
You can change me and i won't forget!
</textarea>
<script>
document.title+=" - Today is " + Date(); // task/title bar demo
h1.innerHTML+= JSON.stringify( App.commandLine ); // optional invocation info here (much like a real app)
// app-specific custom code:
FILENAME="state.txt";
function saveMe(){save(FILENAME, mydata.value); }
function loadMe(){mydata.value=load(FILENAME) || mydata.value;}
// generic utils:
function load(filename) { //IE FSO file Loader
var file,
text="",
fso= new ActiveXObject('Scripting.FileSystemObject');
try{
file = fso.OpenTextFile(filename, 1, false);
text = file.readAll();
file.Close();
}catch(y){}
return text;
}
function save(filename, sData){ //IE FSO file Saver
var file,
fso = new ActiveXObject('Scripting.FileSystemObject');
file = fso.CreateTextFile(filename, 2, false);
file.write(sData);
file.Close();
return file;
}
</script>
</body>
</html>
I recently re-discovered HTAs, and they are not half bad. I don't think I would want to distribute and maintain them, but HTA's are an easy way to make simple desktop app using HTML, CSS, and JS. Its nice not to have to build anything to "recompile" the app after changes are made. saves a few steps compared to node-webkit, packaged apps, air, cordova, etc, but HTA's have a major downside: they only work on windows afaik...
Looks to me like you can use LocalStorage, the big question is how are you trying to store it? You can easily store an object/array into LocalStorage, and that object/array can be your data, then JS can output this into a table. If you're looking to store actual files then you're looking at something more like an ActiveX plugin.
http://caniuse.com/#search=localstorage
Alternatively if you have internet access through a desktop or a phone you can put this on Google Drive. This would be far easier than reinventing the wheel.
I have a .json file in a bucket on S3. I'm trying to parse information from the file, a date and a SigninSim. I am doing this through an html file which once I get this figured out will take that parsed information, go into another folder, and display some pictures. Here is the code that I currently have written.
<!DOCTYPE html>
<html>
<head>
<script src="https://s3.amazonaws.com/'BUCKET'/browser.json"></script>
<script type="text/javascript">
function parseJSON()
{
var info = JSON.parse(browser);
document.write(info.date);
document.write(info.SigninSim);
}
</script>
</head>
<body>
<script type="text/javascript">
parseJSON();
</script>
</body>
</html>
When I run this nothing shows up on the page. Any ideas? I'm also very new to html/javascript so I could be doing something completely wrong, anything helps!
<script> tags can only be used to execute Javascript code, not to read JSON files.
Change the JSON file to a Javascript file that creates global variables or objects.