1

I have some data stored in a JavaScript array which I want to send to some other page. Is it possible to do this without utilizing any server-side scripting like PHP? Can it be done with JS or jQuery or something like that? Ideally, I want to be able to access that array in my JS script on the other page.

Thank you

pajevic
  • 4,607
  • 4
  • 39
  • 73
  • 1
    You can use localStorage or cookies to save this data, then fetch it back at 'some other page'. – raina77ow Dec 24 '12 at 18:23
  • You can try setting a cookie with the data on the first page, and getting the cookie with the data on the second page. – Stegrex Dec 24 '12 at 18:23
  • I think this is a duplicate from [this][1] SO question, chek it out mate. You can send an object to another page if you're opening it from window.open method. [1]: http://stackoverflow.com/questions/87359/can-i-pass-a-javascript-variable-to-another-browser-window – Sam Ccp Dec 24 '12 at 18:24

1 Answers1

2

You can serialize your Array/Objects into a String using

JSON.stringify

so if you have an Array like

var arr = [1,2,3,4]
JSON.stringify(arr) // "[1,2,3,4]"

And then pass it using an GET parameter to your other page

In which you could acces it using something like this

function get(q,s) { 
        s |= window.location.search; 
        var re = new RegExp('&'+q+'(?:=([^&]*))?(?=&|$)','i'); 
        return (s=s.replace(/^\?/,'&').match(re)) ? (typeof s[1] == 'undefined' ? '' :     decodeURIComponent(s[1])) : undefined; 
    }

If you'r url were www.example.com/?arr="[1,2,3]"

get("arr")

Would return

"[1,2,3]"

of course you could also store this String in a Cookie or in the localStorage Object (which is only supported by modern browsers)

Then you can use

JSON.parse

var arr = JSON.parse("[1,2,3,4]");
arr // [1, 2, 3, 4]
Moritz Roessler
  • 8,542
  • 26
  • 51
  • 1
    IE8 supports `localStorage` as well. – John Dvorak Dec 24 '12 at 18:35
  • Thx, i'll add a compatibility table, when i'm back from mobile – Moritz Roessler Dec 24 '12 at 18:44
  • Thank you for the reply Glutamat. I would prefer to use JSON then cookies or localStorage since it seems like a more robust option. However, you mention sending it using POST. It is my understanding that POST can only be read by the server, which is not possible in my case (or else I would just have used PHP). I'm not even sure that GET can work either. How would you go about actually passing the data to the other page once it has been converted into the JSON string? – pajevic Dec 24 '12 at 18:44
  • Ok, so I ended up using your suggestion and passing it through `localStorage`. Keeping my fingers crossed for no old browsers :) – pajevic Dec 24 '12 at 19:08
  • @NobleK Updated the answer with get parameters, sorry i don't had the time to do this nicely, as its christmas and i have no time right now, hope this helps you – Moritz Roessler Dec 24 '12 at 19:10