javascript/jquery local app using json as my DB - javascript

i'm quite new to javascript/jQuery/Json. i'm building myself a local app ( no client side for now). right now i have a simple form (inputs and submit) and would like to get the inputs from the user with javascrip/JQuery and then build a JSON object and store it on a file. i managed to get the inputs using jQuery ,and using JSON.strigify() i have a JSON object. only thing is that i dont know how to write to a file with JS. i searched for a solution and understand that i might need to use PHP for that as JS is not meant for changing files.
here is my code:
HTML form:
<form name="portfolio" id="portfolio" method="post" onsubmit="getform()">
<p>General</p>
Portfolio Name: <input type="text" id="portfolioName" name="portfolioName"><br>
Owner First Name: <input type="text" id="ownerFName" name="ownerFName"><br>
Owner Last Name: <input type="text" id="ownerLName" name="ownerLName"><br>
<p>Risk Management</p>
%stocks : <input type="text" id="stocksPerc" name="stocksPerc"><br>
<input type="submit" value="submit">
</form>
JS code
function getform() {
var portfolioName = document.portfolio.portfolioName.value;
var ownerFname = document.portfolio.ownerFName.value;
var ownerLname = document.portfolio.ownerLName.value;
var stocksPerc = document.portfolio.stocksPerc.value;
var myJsonObject =JSON.stringify({
"general": {
"portfolioName": portfolioName,
"ownerFname": ownerFname,
"ownerLname": ownerLname
},
"riskManagement": {
"stocksPerc": stocksPerc
}
});
alert(myJsonObject);
event.preventDefault();
};
now in "myJsonObject" i have the JSON object which i would like to write to a local file.
later on i would like to read this file ,and maybe update some of the values there.
can someone please help me understand how do i write it to a file ?
you can try and load this page which runs my code. hope it works for you.
note: programming is my area of interest but i didnt study it ,i'm learning all by myself so i'm sorry if i askqdo things that make you blind for a moment :). also this is the first question i post here ,feel free to say if i need to improve.
Thanks
Sivan
update + clarification : Thanks for the answers guys ,localStorage is something i didnt know about. from what i understand about localStorage its only good for working in a single domain/location. (i encountered this question on site). what if i want the option of running the app from different locations - lets say there will be only one person updating the JSON data, no need for sync/lock and stuff like that. right now my files (JS,JSON..) are saved in dropbox ,this is how i can use the app from different locations today , i dont have any other server.
2'nd update : i tried the localStorage solution i've been offered and even though its a great capability ,its not exactly what i'm looking for since i need the JSON data available in more then one location (i'll be using my desktop and my laptop for instance).
i'd be glad if you have other suggestions.
Thanks Again.

Check out the HTML5 localStorage API. You will be able to store your JSON objects there and retrieve them. They will be stored as key-value pairs. You can't write to a file using JS AFAIK.

Don't use a file as storage, use localStorage: http://diveintohtml5.info/storage.html. If you need to save information on a session scope, you should use sessionStorage, mind though that the latter is not persistant.
An example of how you would use it:
var item = {
"general": {
"portfolioName": portfolioName,
"ownerFname": ownerFname,
"ownerLname": ownerLname
},
"riskManagement": {
"stocksPerc": stocksPerc
}
}
// set item, you should think up of a unique key for each item
localStorage.setItem('your-key', item);
// remove it if no longer needed, you don't have a lot of space
localStorage.removeItem('your-key');

Saving files is possible in some browsers but this will probably be removed in the future - so I wouldn't use it unless you must.
This article shows how to -
http://updates.html5rocks.com/2011/08/Saving-generated-files-on-the-client-side
You can post the json to a server and use the server to generate a download file (ask a new question if thats what you seek)
and finally - are you sure you want to save to file? if all you want is to save and restore data then there are better alternatives (such as localStorage, cookies, indexDb)

Related

How to query JSON with JS API to return JSON properties?

Apologies if this seems basic to some, but I'm new to JS/node.js/JSON and still finding my way. I've searched this forum for an hour but cannot find a specific solution.
I have a basic website setup running of a local Node.js server along with 2x JSON data files with information about 32x local suburbs.
An example of an API GET request URL on the site would be:
.../api/b?field=HECTARES
The structure of the JSON files are like:
JSON Structure
In the JSON file there are 32x Features (suburbs), each with it's own list of Properties as shown above. What I am trying to do is use the API 'field' query to push all the HECTARES values each of the 32x Features into a single output variable. The code below is an example of how far I have got:
var fieldStats = [];
var fieldQ = req.query['field'];
for (i in suburbs.features) {
x = suburbs.features[i].properties.HECTARES;
fieldStats.push(x);
}
As you can see in the above "HECTARES" is hard-coded - I need to be able to pass the 'fieldQ' variable to this code but have no idea how to.
Advice appreciated!
Exactly the same syntax you are using just above:
suburbs.features[i].properties[fieldQ];

I am unable to retrieve localStorage data, as stored format appears different?

I am a newbie to programming, and apologies in advance if this has been answered before. I have done some searches and it doesn't look to me like this specific question has been answered.
Before attempting to store a large volume of data in localStorage (HTML5, Chrome, Windows), I have tried some sample data and attempted to store data. When I do a console display before storing the variable shows all the data correctly. I also seem to have some success because I see the sample data in the localStorage via the console.
However, I am baffled that the data appears multiple times in a continuous line. When I try to retrieve the data with a getItem, I get a null. I am not doing anything fancy for either storing or for retrieving data.
The code I use for storing and retrieving are shown below, as also the data in the localStorage as viewed by the Chrome console.
I have also tried JSONstringify in one of my attempts.
Storing:
window.localStorage.setItem('result', zlldata);
Retrieving:
GETzlldata = window.localStorage.getItem(zlldata);
zlldata = JSON.parse(GETzlldata);
Data in the LS look like this: (I tried 2 different approaches, once with 'this.zlldata' and the other time with 'result' in the setItem attempts.
this.zlldata: "undefined"
{"zipLatLong": [
{"zipcode":"35004","lat":"33.606379","longit":"-86.50249"},
{"zipcode":"35005","lat":"33.592585","longit":"-86.95969"},
{"zipcode":"35006","lat":"33.451714","longit":"-87.23957"},
{"zipcode":"35007","lat":"33.232422","longit":"-86.80871"}
]
}
{"zipLatLong": [
{"zipcode":"35004","lat":"33.606379","longit":"-86.50249"},
{"zipcode":"35005","lat":"33.592585","longit":"-86.95969"},
{"zipcode":"35006","lat":"33.451714","longit":"-87.23957"},
{"zipcode":"35007","lat":"33.232422","longit":"-86.80871"}
]
}
Question I have is how do I retrieve the data. I mentioned that data looks different because of all the 'return' characters that show up. Regardless the data should be 'retrievable'. I have allocated enough space in localStorage for the purpose at 5 MB. The format is the same for all records. The purpose of this exercise is a project that I am doing for the course and this approach has other uses. I am aware that in the real world other easier ways are available (e.g. via APIs to websites).
Appreciate any help. Just as additional info, I don;t need to retrieve all data each time, but only need to validate that the zipcode (for eg, exists)
Thanks again in advance and sorry for the lengthy post
To put complex data into localStorage:
localStrorage.setItem("name", JSON.stringify(theData));
To read complex data out of localStorage:
var theData = JSON.parse(localStorage.getItem("name") || "null");
if (theData) {
// It wasn't there, initialize it
}
(Naturally, the above only works with values that can be converted to and from JSON. If you have values that don't convert readily, like dates, you can use a replacer function with JSON.stringify and a reviver function with JSON.parse to handle them.)
Full example on jsFiddle (Stack Snippets don't allow localStorage): https://jsfiddle.net/aj2mq4rz/1
HTML:
<div>
<label>
Name:
<input type="text" id="field-name">
</label>
</div>
<div>
<label>
Age:
<input type="text" id="field-age">
</label>
</div>
<input type="button" id="btn-save" value="Save">
JavaScript:
// On page load, read our data
var theData = JSON.parse(localStorage.getItem("someName") || "null");
if (!theData) {
theData = {
name: "",
age: 0
};
}
var nameField = document.getElementById("field-name");
nameField.value = theData.name;
var ageField = document.getElementById("field-age");
ageField.value = theData.age;
document.getElementById("btn-save").onclick = function() {
// Update our object
theData.name = nameField.value;
theData.age = +ageField.value;
// And save it to local storage
localStorage.setItem("someName", JSON.stringify(theData));
}
You are using:
window.localStorage.setItem('result', zlldata); for storing but using window.localStorage.getItem(zlldata);for retrieving. You cannot retrieve with the value, you need to use the key. So, you need to use getItem('result');
I wrote a tool that will do this for you, that is, allow you to transparently set and get a javascript object (and other primitives) as a localStorage key value. (It does the conversion so you don't have to.) It's called localDataStorage.
To use it, first instantiate your storage object:
localData = localDataStorage( 'my.project' );
Then, store a key value (in this case, your object unchanged):
localData.set( 'key1', '{"zipLatLong": [{"zipcode":"35004","lat":"33.606379","longit":"-86.50249"},{"zipcode":"35005","lat":"33.592585","longit":"-86.95969"},{"zipcode":"35006","lat":"33.451714","longit":"-87.23957"},{"zipcode":"35007","lat":"33.232422","longit":"-86.80871"}]}' );
Then, read it back:
x = localData.get( 'key1' );
--> "{"zipLatLong": [{"zipcode":"35004","lat":"33.606379","longit":"-86.50249"},{"zipcode":"35005","lat":"33.592585","longit":"-86.95969"},{"zipcode":"35006","lat":"33.451714","longit":"-87.23957"},{"zipcode":"35007","lat":"33.232422","longit":"-86.80871"}]}"

Can I secure this javascript code in a database?

I currently have this code and I want to know how to store it, and then use it, in a database:
var stores = {
"McDonalds" : .90,
"Target" : .92,
"iTunes" : .95,
"Starbucks" : .87,
"Best Buy" : .93,
}
This list will be different and much bigger, but thats an example. It is currently put into action using:
<script src="location"></script>
I want to hide it in a database so that it isn't accessible to customers or competitors. How can I do that? And, when doing so, how would I then have my page access it instead of using script src?
You can't hide this from your customers, and still have your customers use that data in their browser. That isn't how the Internet works. If the browser needs to read that data, the user can also read that data.
If you can move whatever calculation you're doing server-side, that might be an option, but these are pretty simple values, and I'm guessing that people will have little difficulty guessing them simply by examining the inputs and outputs of your algorithm.

Jira Gadget: Configuration isn't saved for reconfiguration

I am writing a gadget for Jira with some configuration options. One of these configuration options is a "project or filter picker".
My problem lies in the part, when I want to reconfigure the gadget's preferences. I have read the code of the timesince-gadget as an example and I think the relevant part is the following:
if (/^jql-/.test(gadget.getPref("projectOrFilterId"))){
projectAndFilterPicker =
{
userpref: "projectOrFilterId",
type: "hidden",
value: gadgets.util.unescapeString(this.getPref("projectOrFilterId"))
};
} else {
projectAndFilterPicker = AJS.gadget.fields.projectOrFilterPicker(gadget, "projectOrFilterId", args.options);
}
Basicly I've copied the code from the timesince-gadget. Unfortunately even if already configured, the javascript always enters the else part.
A problem is, that I ve no experience with jql and don't totally understand the if clause.
But usually (e.g. when calling the rest api and processing the config infos)
gadget.getPref("projectOrFilterId")
returns a string containing the id of the picked project or filter.
Question is now: How can I make my gadget remember the last configuration like it's done with some many other Jira gadgets?
I really hope anyone can help me with that.
It turnes out, the answer is even simplier then I thought.
First: In the descriptor you can totally forget the if part from above. Just
var projectAndFilterPicker = AJS.gadget.fields.projectOrFilterPicker(gadget, "projectOrFilterId", args.options);
is needed.
Second: Retrieve the project's or filter's name in your rest resource, which shouldn't be a problem, since you already want to use the processed id. Then return this name back to the view part of your javascript and type in something like
this.projectOrFilterName = args.myrestclasskey.projectOrFilterName;
And tada: reconfiguration will display the old configured name!
I had this problem once when I forgot to specify the option in the Gadget XML file. I solved it by adding this to the XML:
<UserPref name="projectOrFilterId" datatype="hidden"/>

Local HTML 5 database usable in Mac Dashboard wigdets?

I'm trying to use HTML 5's local database feature on a Mac Dashboard widget.
I'm programming in Dashcode the following javascript:
if (window.openDatabase)
{
database = openDatabase("MyDB", "1.0", "Sample DB", 1000);
if (database)
{
...database code here...
}
}
Unfortunately the database-variable remains always null after the call to openDatabase-method. I'm starting to think that local databases are not supported in Widgets...
Any ideas?
/pom
No you will not be able to do the above. And even if you could then you would not be able to distribute the widget without distributing the database assuming it was a MySQL or SGLite. (not sure what you mean by HTML 5's local Db.
here are a number of ways round this:-
You can add a data source which can be a JSON file, or an XML file or and RSS feed. So to do this with JSON for example you would write a page on a server in PHP or something that accessed a database so that when the URL was called the result was a JSON string. Take the JSON string and parse it and use it in the Widget. This will let you get data but not save it.
Another way would be to use the user preferences. This allows you to save and retrieve data in the individual widget.
So
var preferenceKey = "key"; // replace with the key for a preference
var preferenceValue = "value"; // replace with a preference to save
// Preference code
widget.setPreferenceForKey(preferenceValue, preferenceKey);
You can then retrieve it with
var preferenceForKey = "key"; // replace with the key for a preference
// Preference code
preferenceForKey = widget.preferenceForKey(preferenceForKey);
The external call, you could also use REST will let you read any amount of data in and the preferences will let you save data for later reuse that will survive log out's and shut downs.
The Apple site has a lot of information about Widgets and tutorials as well thjat are worth working through.
Hope this helps.

Categories