I was wondering if it\'s possible to store the return json in a hidden input field. For example this is what my json return:
[{\"id\":\"15aea3fa\",\"firstnam
Although I have seen the suggested methods used and working, I think that setting the value of an hidden field only using the JSON.stringify breaks the HTML...
Here I'll explain what I mean:
As you can see the first double quote after the open chain bracket could be interpreted by some browsers as:
So for a better approach to this I would suggest to use the encodeURIComponent function. Together with the JSON.stringify we shold have something like the following:
> encodeURIComponent(JSON.stringify({"name":"John"}))
> "%7B%22name%22%3A%22John%22%7D"
Now that value can be safely stored in an input hidden type like so:
or (even better) using the data- attribute of the HTML element manipulated by the script that will consume the data, like so:
Now to read the data back we can do something like:
> var data = JSON.parse(decodeURIComponent(div.getAttribute("data-json")))
> console.log(data)
> Object {name: "John"}