Skip to content Skip to sidebar Skip to footer

How I Can Store Javascript Array Object Saved Somehow So That I Can Use It Later

I have a situation like follows: I have a id select page where user can select id from the shown ids on the page.When the user select the id i store them as a comma seperated value

Solution 1:

Here's a JSFiddle.

If you want to store the object in an input field, you can use JSON.stringify():

 //Pass your array (or JSON object) into JSON.stringify:
 JSON.stringify([{id:1, product_id: 2, name: 'stack'},
                 {id: 2, product_id: 2, name: 'overflow'}] )

which will yield:

"[{"id":1,"product_id":2,"name":"stack"},{"id":2,"product_id":2,"name":"overflow"}]"

You can store this value in a hidden field (or a data attribute):

 <input type="hidden"id="project" value="[{'id':1,'product_id':2,'name':'stack"',{'id':2,'product_id':2,'name':'overflow'}]" />

Obviously, you can combine these steps (or do it through PHP / Rails / ...)

 $('#project').val(JSON.stringify([1,2,3]));

You can then decode this using, for instance, jQuery:

 $.parseJSON($('#project').val());

This should allow you to use the process you are using, but store Javascript objects in your input fields. Hope this helps!

Solution 2:

You can

  1. store the value in memory, using JS

    var arr = [];
    arr.push(your_value);
    
  2. keep creating new attribute/values in the dom using JS
  3. pass the value from page to page through the query string
  4. store the value in a cookie to be retrieved again
  5. store the value on the server (in a file/db) to retrieve again

Note: Options 3 and 5 are only meaningful if you want to go to another page (on the site). Options 4 and 5 are good if you want to close the browser and retrieve that info at a later point.

Solution 3:

If you are not worried about IE7, you can use localStorage:

window.localStorage.setItem('myArray', JSON.stringify([234,678,987]));
// retrievevar myArray = JSON.parse(window.localStorage.getItem('myArray'));

The JSON is supported by modern browsers. You can add it by including json2.

Solution 4:

I assume you're talking about preserving the data after a new page has loaded. You can use your current approach of storing the data as a string in a hidden input, and then parse that string into a JavaScript object later. Another option is that your server-side code can produce some inline JavaScript declaring the JavaScript object you need. If you're using ASP.NET, for example, your page could have something like this:

// Assuming "serverSideIds" is declared as a List<string>

<% var serializer = new JavaScriptSerializer(); %>
var ids = <%= serializer.Serialize(serverSideIds) %>;

Post a Comment for "How I Can Store Javascript Array Object Saved Somehow So That I Can Use It Later"