binding nested json object value to a form field - javascript

I am building a dynamic form to edit data in a json object. First, if something like this exists let me know. I would rather not build it but I have searched many times for a tool and have found only tree like structures that require entering quotes. I would be happy to treat all values as strings. This edit functionality is for end users so it needs to be easy an not intimidating.
So far I have code that generates nested tables to represent a json object. For each value I display a form field. I would like to bind the form field to the associated nested json value. If I could store a reference to the json value I would build an array of references to each value in a json object tree. I have not found a way to do that with javascript.
My last resort approach will be to traverse the table after edits are made. I would rather have dynamic updates but a single submit would be better than nothing.
Any ideas?
// the json in files nests only a few levels. Here is the format of a simple case,
{
"researcherid_id":{
"id_key":"researcherid_id",
"description":"Use to retrieve bibliometric data",
"url_template" :[
{
"name": "Author Detail",
"url": "http://www.researcherid.com/rid/${key}"
}
]
}
}
$.get('file.json',make_json_form);
function make_json_form(response) {
dataset = $.secureEvalJSON(response);
// iterate through the object and generate form field for string values.
}
// Then after the form is edited I want to display the raw updated json (then I want to save it but that is for another thread)
// now I iterate through the form and construct the json object
// I would rather have the dataset object var updated on focus out after each edit.
function show_json(form_id){
var r = {};
var el = document.getElementById(form_id);
table_to_json(r,el,null);
$('body').html(formattedJSON(r));
}

A much simpler approach would be to accept a form submission and output the data in JSON format. That way, there is no need to bind variables.

The solution has arrived. JQuery now has plugins for data binding and templates.
http://www.borismoore.com/2010/09/introducing-jquery-templates-1-first.html
http://api.jquery.com/jQuery.template/
http://api.jquery.com/category/plugins/data-link/

There is another simple template engine that loads JSON data directly into the form. See http://plugins.jquery.com/project/loadJSON plugin. It works similar way as the one that Jack placed here but it uses plain HTML for template.
You can see instructions how to use it on the http://code.google.com/p/jquery-load-json/wiki/WorkingWithFormElements and live example on the http://jquery-load-json.googlecode.com/svn/trunk/edit.html?ID=17.

Related

Get Data from Text File to Multidimensional Array Javascript

I have a little bit of an issue with a JavaScript function that needs to read data from a TextFile (something JS is already limited with) and then process tha TextFile data into a MultiDimensional Array (another thing that JS doesn't nativelly suport).
With that in mind, I have a text file in this format:
1, Name, Data, Serial
2, Name, Data, Serial
3, Name, Data, Serial
And so on.
So, the objective is to get that same data and put it, like that, into an array.
I suppose that, from what I've been reading, I need an Array of an Array, segmenting the first one by lines [/n] and the second one by commas [,]. However, given the "by-default" limitations, I'm very confused at this point. I do suppose I need jQuery, however.
I tried this:
var fs = require('fs');
var array = fs.readFileSync('file.txt').toString().split("\n");
for(i in array) {
var array = fs.readFileSync('file.txt').toString().split(",");
for(f in array) {
}
}
With little success, because then I don't really know how to store it, the objective being a Multidimensional Array that Replicates the Format of the text file, so latter it could be used to search by index or instance following an user input to get results.
I really appreciate any help.
At first glance it seems like you are trying to read in a CSV file. If that is indeed the case I recommend node-csv:
http://www.adaltas.com/projects/node-csv/
https://github.com/wdavidw/node-csv
This helped me reading file to JavaScript, however this example converts retrieved data to JSON. Just looking at the format of your text file, I would assume a JSON string or Javascript object would work with your data.
Example convert to JSON
With JSON and JS objects, instead of referencing a array indexes eg. array[i][x]. you would replace [x] with .propertyName
data = {
"id": 1,
"name": "Fred"
};
//access data like this
data[i].name //will return "Fred" as i =0
to create JS object, just initialize array properties without the ""(quotation marks). accessing JS and JSON properties are done in the same way, main advantage over a multidimensional array is that you can reference an actual property name, as opposed to indexes.

Is it possible to store a JSON object directly into the DOM somehow?

If one has the output of a JSON.parse readily at hand, is there some legitimate way of storing that object in the DOM as a single entity?
i.e.
jsonObject = JSON.parse(something);
I'd like to consider storing the jsonObject in the DOM as a (child || textNode || ???) of some element and later retrieving it so that immediately after retrieval I could access its contents via the usual:
jsonObject.keyName
I want to avoid adding dozens of dataset attributes and later being forced to extract them one at a time. That's too much work and seems too inefficient if you have dozens of key:value pairs.
Data attributes have to be strings, you can't store objects in them directly. So don't parse the JSON string, just store the JSON string directly in the dataset attribute.
If you use jQuery, its .data() method will take an object, and it will automatically stringify it as needed.
If the elements you want to associate the object with all have IDs, another option is to use a global object as a table, keyed off the element's ID.
jsonTable[id] = jsonObject;
It depends on the life cycle of your page. If you don't intend to reload the page it's better to just leave it as a JavaScript variable on the page.
You can also consider storing the raw JSON in a hidden filed or some other hidden DOM element. Keep in mind though that hidden fields will be posted to the server if you do a post of the page
TGH has the right answer. Leave it as a variable.
An alternative is to use history.pushState() to store it along with the URL to your page. This is helpful if you ever want the user to be able to click the back button and have the json restored to the value it had for that page.
If you want to store a data (JSON) associated with DOM element.
You could use jQuery data function.
e.g., store a JSON to a restaurant row (div)
$("div.restaurant-row").data("info",{purchases: "blablabla", mealFormulas: "xxxxx"});
e.g., fetch DOM associatd data
$("div.restaurant-row").data("info").purchases; //blablabla
I'm not sure if this is what you want.
Hope this is helpful for you.

pass multidimensional javascript array to another page

I have a multidimensional array that is something like this
[0]string
[1]-->[0]string,[1]string,[2]string
[2]string
[3]string
[4]-->[0]string,[1]string,[2]string[3]string,[4]string,[5]INFO
(I hope that makes sense)
where [1] and [4] are themselves arrays which I could access INFO like myArray[4][5].
The length of the nested arrays ([1] and [4]) can varry.
I use this method to store, calculate, and distribute data across a pretty complicated form.
Not all the data thats storred in the array makes it to an input field so its not all sent to the next page when the form's post method is called.
I would like to access the array the same way on the next page as I do on the first.
Thoughts:
Method 1:
I figure I could load all the data into hidden fields, post everything, then get those values on the second page and load themm all back into an array but that would require over a hundred hidden fields.
Method 2:
I suppose I could also use .join() to concatenate the whole array into one string, load that into one input, post it , and use .split(",") to break it back up. But If I do that im not sure how to handel the multidimensional asspect of it so that I still would be able to access INFO like myArray[4][5] on page 2.
I will be accessing the arrary with Javascript, the values that DO make it to inputs on page 1 will be accessed using php on page 2.
My question is is there a better way to acomplish what I need or how can I set up the Method 2 metioned above?
This solved my problem:
var str = JSON.stringify(fullInfoArray);
sessionStorage.fullInfoArray = str;
var newArr = JSON.parse(sessionStorage.fullInfoArray);
alert(newArr[0][2][1]);
If possible, you can use sessionStorage to store the string representation of your objects using JSON.stringify():
// store value
sessionStorage.setItem('myvalue', JSON.stringify(myObject));
// retrieve value
var myObject = JSON.parse(sessionStorage.getItem('myvalue'));
Note that sessionStorage has an upper limit to how much can be stored; I believe it's about 2.5MB, so you shouldn't hit it easily.
Keep the data in your PHP Session and whenever you submit forms update the data in session.
Every page you generate can be generated using this data.
OR
If uou are using a modern browser, make use of HTML5 localStorage.
OR
You can do continue with what you are doing :)

How should i save the response data in a object(json) to have better manipulation and performance?

what i am doing is:
1. Get values from ajax response(which is in json format) for listing rows of data which
response = {"categories":[{"name":"General","id":"6305","pop":"show when clicked"},{"name":"Navigation","id":"6043","pop":"show when clicked"},{"name":"New","id":"6051","pop":"show when clicked"},{"name":"Time","id":"6117","pop":"show when clicked"},{"name":"Reesh","id":"6207","pop":"show when clicked"}]}
2 . I will parse the json and store in a object like this
ex:
object= {6305:{"name":"General","id":"6305","pop":"show when clicked"},
6043:{"name":"Navigation","id":"6043","pop":"show when clicked"},
6051:{"name":"New","id":"6051","pop":"show when clicked"},
6117:{"name":"Time","id":"6117","pop":"show when clicked"},
6207:{"name":"Reesh","id":"6207","pop":"show when clicked"}};
why i am doing this is because i can get the data using the id
ex: object[6305] will give me the data.
3 .So that i can retrieve the data and also make changes to values in the object using the id when changes occur in db.
ex: object[6350].pop="changed";
Please tell me:
-->whether is this the correct method or i can do it in a much simpler or efficient way?
-->whether i can store the json response as it is and parse data as it is? if so please explain with example.
Yes, of course you would not need to build the object:
function getObject(id) {
for (var i=0; i<response.categories.length; i++)
if (response.categories[i].id == id)
return response.categories[i];
return null;
}
However, if you often need to access objects by their ids this function would be slow. Creating the lookup table as you did will not create much memory overhead, but make retrieving data much faster.
BTW: Your title question "save data as object or json" is confusing. Serializing manipulated objects back to JSON makes no sense, as you always will use the parsed objects. Of course, if you just needed to manipulate a JSON string, and knew exactly what to do, (simple) string manipulation could be faster than parsing, manipulating and stringifying.

Capturing form data: variables or array?

I have a form with about 20 input fields. I capture values of these fields, then do some calculations and output several values.
Is there a preferred/recommended way of capturing form data? Currently I store every form field into a separate variable. I was wondering if storing it to an array would be a better and more effective approach.
I'm quite new to Javascript and programming in general, trying to learn the best practices.
My best practice on this depends on what I have to do with the data. If I do not need to loop through it, or send it to another page/service, then there's nothing wrong with individual scoped-variables.
If I need to loop at all, I commonly use an array or object to loop through.
If I have to pass it to another page/service, I make one object variable to encapsulate the rest of them, so I can "stringify" it to JSON and parse back to an object on the other end.
Just my opinion,
Pete
You might consider the third approach - just use the data from the form without storing it anywhere.
First check the correctness, once it is considered correct just use what you have.
You should always assign the attribute "name=..." to an input element, so you can use something like:
var form = document.forms['form'];
var email = form['email'];
email = do something
if you use javascript... if you use jquery it's simple $('input[name="email"]') = do something
I prefer this way because you can call variables by name, not by number, for example "form[0] that corresponds to input[name="email"]".
Use the associative properties of arrays in JavaScript to get the benefits of unique field names and OOP:
var formModel = new Array();
formModel['myField'] = getMyFieldValue(); // make 'myField' index to any object
Then you can do things like:
formModel['myField'] // get the value
formModel.length; // number of fields added
for (entry in formModel) { /* loop thru entries */ }
formModel.sort([compareFunction]) // custom sort
formModel = []; // clear the model
Convert array to JSON
Any of these ArrayMDN conveniences.
Just one approach, but arrays in JS are extremely versatile and IMO underused objects in JS.

Categories

Resources