sharing a JSON object among HTML files using JavaScript - javascript

I have an HTML page and a java script file. When I click on a button in my html page I get a Json string in the java script file from the server. The Json string contains data that I want to use in other Html pages, so what would be a good technique to share the json string or object among the html pages, using java script only???
thx

I don't know if that counts as "JavaScript only", but you could use DOM Storage.
window.localStorage.setItem('theData', theData)
That way it even survives closing the window (which you may or may not want).

You could use unique URI REST-style requests for Your data, together with cache headers, so Your browser could use it's native page caching.

PersistJS is a wrapper around the new storage features in modern browsers (LocalStorage,globalStorage,openDatabase, gears,...). It uses feature detection to select the most appropriate storage solution. Including falling back to Cookies/Flash on older browsers.
http://pablotron.org/software/persist-js/
or more details on how it works at: http://pablotron.org/?cid=1557

Using JavaScript only you can go for cookies but they will be limited in size or you can go the new shiny HTML5 Local Storage if you only need to cater modern browsers.
EDIT: You have to open your HTML files through server if you use these, not directly by double clicking!

Related

Saving / Retriving all the fields value's of an HTML form into / from a local file using JavaScript

I have a typical HTML form, with some fields of various types on it.
What I'm trying to achieve is the following:
Once the form's input fields are filled out with values, a button to be able to save all the filled-out field/value pairs into a local file of some sort that allows me in a future ocassion to...
Automatically fill the very same HTML form by retriving the field/values pairs from said file instead of typing them manually.
Ideally this would have to be achived thru JavaScript, because the webpage that contains the HTML form is served by an embedded system where PHP or other server side scripting is not available.
Is it possible to achive this thru JavaScript (or any other browser-side effort method)? If so, how?
Many thanks.
EDIT: The target environment is a regular user in a regular PC/laptop using any one of the 4 major browsers. It's acceptable to have "Cookies enabled" and "latest browser version installed" as requisites, but external plugins/addins are not.
Later: NullUserException has achived something in this direction. He's been able to read from a local file using JavaScript:
Using a local file as a data source in JavaScript
I think, for your particular site you can store data in local storage. Only your application will be able to access to that data. Also you can encrypt it before storing.
You can refer
diveintohtml5.info/storage to start with.
Happy coding.
Pretty sure you won't be able to save a file locally and then pick it up again.
However there are obviously cookies but there, and this is only in a modern browser, is also LocalStorage that can hold quite a bit of data that can be retrieved by Javascript and jQuery.
This is probably the way I would go but it does depend on your browser version.
question is some what ambiguous please specify what you are trying to do.
i can't tell if you want to do something just for you if so:
https://addons.mozilla.org/en-US/firefox/addon/greasemonkey/

How to locally fetch JSON without AJAX

I'm building a game using HTML5 Canvas and Javascript and I'm using JSON formatted tile maps for my levels. The tiles render correctly in FireFox, but when I use Chrome, the JSON fetching fails with a "Origin null is not allowed by Access-Control-Allow-Origin." I was using jQuery's $.ajax command and all my files are in one directory.
I would use this post's solution, but I can't use the web server solution.
Is there any other way to fetch JSON files to be parsed and read from? Something akin to loading an image just by giving the URL? Or is there some way to quickly convert my JSON files into globally available strings so I can parse it with JSON.parse()?
Why is the local web server not an option? Apache is free, can be installed on anything, and easy to use, IMO. Also, for Chrome specifically, look into --allow-file-access-from-files
But if nothing else works, maybe you could just add links to the files in script tags, and then append var SomeGlobalObject = ... to the top of each file. You might even be able to do this dynamically by using JS to append the script tag to head. But in the end, instead of using AJAX, you can just do JSON.parse(SomeGlobalObject)
In other words, load the files into the global namespace by adding script tags. Normally this would be considered bad practice, but used ONLY for testing, in the absence of any other options, it may work.
One option which may work for you in Chrome is to invoke the browser with the command line switch --allow-file-access-from-files. This question addresses the issue : Google Chrome --allow-file-access-from-files disabled for Chrome Beta 8
Another possibility is to fetch the JSON data as a script, setting a global variable to the JSON value

how to keep javascript objects alive in a multi-page html5 app?

How can I keep javascript objects alive in a multi-page app (browser independently)?
I know I can for example write a Chrome extension with a background page that would solve it, but is there a browser independent way for this?
One approach is to have your javascript code load the pages (via 'ajax' calls) and then replace the body of the html, or parts of it. This way, as far as the browser is concerned you're still on the same "page". You'll have to make sure all the links within your website are void and instead of causing a browser page load, they actually trigger a javascript function. This is the way Facebook, for example, manages clicks on its website. See https://stackoverflow.com/a/7425870/562906
As you are using html5 you could use local storage to store JSON representations of your objects:
var json_text = JSON.stringify(your_object, null, 2);
localStorage.setItem("someKey", json_text);
and then to retrieve your item when on the other page:
var your_object = JSON.parse(localStorage.getItem("someKey"));
To use JSON.stringify you may need JSON-js - if the browser does html5 it appears likely that you won't need the third party script.
You can use cookies to pass data between page requests. Apart from that, you always have to reconstruct your objects from the beginning.

Save entire files using localStorage

I would like to use localStorage to 'cache' some JS and CSS files in a web app that is primarily used on mobile devices (i.e., bandwidth restrictions). I'm thinking it would work something like this:
The page loads with a small setup.js containing code that checks localStorage to see if bigScriptFile.js has been stored previously.
If it's not stored, bigScriptFile.js is downloaded and stored for the next visit.
If it has been stored, then bigScriptFiles.js is read from localStorage and loaded/run as if it was downloaded like a normal file (i.e., <script src="http://example.com/bigScriptFile.js"></script>)
What I'm not sure how to do is step 1.1 -- storing the JS file. (I know that I can only store strings in localStorage and I know how to use JSON.stringify().)
Surely it's not as simple as using escape():
localStorage.setItem('bigScriptFile', escape('myJScode')) to store, and
unescape(localStorage.getItem['bigScriptFile']) when retrieving
Even if it is that easy, how do I use JS to get the contents of bigScriptFile.js as a string? Perhaps by making an ajax call to a PHP script that returns the contents?
You should rather put the correct cache headers on js files or look at the HTML5 cache manifest.
W3C specification.
Have you seen http://addyosmani.github.com/basket.js/ might work for what you intended to do

Command line URL fetch with JavaScript capabliity

I use curl, in php and httplib2 in python to fetch URL.
However, there are some pages that use JavaScript (AJAX) to retrieve the data after you have loaded the page and they just overwrite a specific section of the page afterward.
So, is there any command line utility that can handle JavaScript?
To know what I mean go to: monster.com and try searching for a job.
You'll see that the Ajax is getting the list of jobs afterward. So, if I wanted to pull in the jobs based on my keyword search, I would get the page with no jobs.
But via browser it works.
you can use PhantomJS
http://phantomjs.org
You can use it as below :
var page=require("webpage");
page.open("http://monster.com",function(status){
page.evaluate(function(){
/* your javascript code here
$.ajax("....",function(result){
phantom.exit(0);
}); */
});
});
Get FireBug and see the URL for that Ajax request. You may then use curl with that URL.
There are 2 ways to handle this. Write your screen scraper using a full browser based client like Webkit, or go to the actual page and find out what the AJAX requesting is doing and do request that directly. You then need to parse the results of course. Use firebug to help you out.
Check out this post for more info on the subject. The upvoted answer suggests using a test tool to drive a real browser.
What's a good tool to screen-scrape with Javascript support?
I think env.js can handle <script> elements. It runs in the Rhino JavaScript interpreter and has it's own XMLHttpRequest object, so you should be able to at least run the scripts manually (select all the <script> tags, get the .js file, and call eval) if it doesn't automatically run them. Be careful about running scripts you don't trust though, since they can use any Java classes.
I haven't played with it since John Resig's first version, so I don't know much about how to use it, but there's a discussion group on Google Groups.
Maybe you could try and use features of HtmlUnit in your own utility?
HtmlUnit is a "GUI-Less browser for
Java programs". It models HTML
documents and provides an API that
allows you to invoke pages, fill out
forms, click links, etc... just like
you do in your "normal" browser.
It has fairly good JavaScript support
(which is constantly improving) and is
able to work even with quite complex
AJAX libraries, simulating either
Firefox or Internet Explorer depending
on the configuration you want to use.
It is typically used for testing
purposes or to retrieve information
from web sites.
Use LiveHttpHeaders a plug in for Firefox to see all URL details and then use the cURL with that url.
LiveHttpHeaders shows all information like type of method(post or get) and headers body etc.
it also show post or get parameters in headers
i think this may help you.

Categories