pass multidimensional javascript array to another page - javascript

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 :)

Related

Storing a php array client side

I have a web page that queries a database to get a list of products with their related data like price, size,weight e.t.c and displays it to the user, I want to add one of those sort dropdown list so that a user can sort the products by price or any other key I specify.
I plan to do it using Ajax on dropdown change query the database again and use the selected value as the sort key in the query.
My question is, is there a way that this can be done client side without running another query? Can php send the query result to the browser and store it there and then use jquery to sort it over and over again?
Thanks everyone for the help!
There are many ways this can be achieved. A simple example can be done with HTML5 LocalStorage.
Here's a general overview of how that can be done:
You make an initial call to your DB for products via AJAX, returns a JSON object.
You serialize that JSON object via javascript e.g. var stringData = JSON.stringify(data)
Store said variable into localstorage: window.localStorage.setItem("products", stringData);
You can then later access it via var products = window.localStorage.getItem("products) and finally deserialize it with var productsObj = JSON.parse(products) or do it all in one c-c-c-c-c-combo breaker: productsObj = JSON.parse(window.localStorage.getItem("products))
Do as you please by using filtering functions!
Another way is to store the initial JSON object using some form of store e.g. Redux, but let's save that for another day ;)
And of course, you may optionally have a globally accessible object that you can assign the initial JSON data to as a property and later access as you would any other property.
Take a look at this jquery plugin
http://tablesorter.com/docs/example-ajax.html
Maybe it's what you are looking for? No need to requery the database.

Passing values from a page to another page in HTML mobile app

I've made users to enter some values in a html page:
Here is the code:
$(function() {
$("#savesymptoms").bind(
"click",
function() {
var url = "notes.html?acne="
+ encodeURIComponent($("#acne").val())
+ "&back="
+ encodeURIComponent($("#bloat").val());
window.location.href = url;
});
});
And I've added an alert like this:
alert("values passed");
But I'm not sure that this is working. I've got some 10 values to pass to another page. Above code contains only two values. Can I use arrays to pass all 10 values? I don't want to use nomenclature used in my code, i.e., individual value passing.
P.S: acne and bloat are the ids of the fields where user enters the data. notes.html is the page where I want to pass the data.
In my opinion you can use sessionStorage in HTML5
For setting a value
sessionStorage.setItem('name', 'value');
For getting the value:
sessionStorage.getItem('name');
if you want to store the value permanently use localStorage.
Since you have almost 10 values push all those values in a JSON and store it either in sessionStorage/localStorage.
You can retrieve it else where and use as per your wish
Note:values stored will be in the form of string even if you push it as JSON.You will have to make it to JSON using Jquery functions
Alternative
You can store it as window.name
But this will be only valid till the window lasts/tab closed(same as sessionStorage)

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.

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.

binding nested json object value to a form field

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.

Categories

Resources