51

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","firstname":"John","lastname":"Doe"}]

I would like to just store the id in a hidden field so I can reference it later to do something with it.

Example: I have something like this:

<input id="HiddenForId" type="hidden" value="" />

and would like jquery to return the value later to me like so:

var scheduletimeid = $('#HiddenForId').val();
Davide Pastore
  • 8,678
  • 10
  • 39
  • 53
hersh
  • 1,173
  • 2
  • 13
  • 26
  • see it too: http://stackoverflow.com/questions/11118947/jquery-equivalent-for-json-stringify –  Sep 28 '12 at 12:40

7 Answers7

161

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:

<input type="hidden" value="{"name":"John"}">

As you can see the first double quote after the open chain bracket could be interpreted by some browsers as:

<input type="hidden" value="{" rubbish >

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:

<input type="hidden" value="%7B%22name%22%3A%22John%22%7D">

or (even better) using the data- attribute of the HTML element manipulated by the script that will consume the data, like so:

<div id="something" data-json="%7B%22name%22%3A%22John%22%7D"></div>

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"}
rodu
  • 2,308
  • 3
  • 15
  • 6
  • 18
    This is the only approach to use if you need to return complex objects in a form POST. It should be the accepted answer (because most people searching and finding this question are wanting to do exactly that). – Aaron D May 31 '15 at 06:30
  • Best solution so far, this should be accepted answer. – digz6666 Aug 27 '15 at 09:14
  • 2
    Wow best solution I've a problem with JSON.stringify for 2 hours then I found this mind blow answer. Thank you. – Sarin Suriyakoon Sep 04 '15 at 18:25
  • Worked for me when using an `input` element, but not when using a `div`. Great solution. – System.Cats.Lol Feb 11 '16 at 23:14
  • I used JSON.stringify() but the value did not appear on the input element. But I can work with this now, awesome solution. – andhikaribrahim Dec 06 '16 at 16:34
  • To avoid parse error, use single quote inside your input tag, e.g. – bzuo Jan 18 '21 at 07:46
  • This is exactly what I needed! – Mark_ Jan 22 '22 at 11:12
  • This is great but if your backend runs something different than JavaScript, it requires some work to ensure that it can properly decode it. An alternative would be to use base64 (btoa) which can be easily decoded on the other side without thinking about it. (I posted an answer below). – Maciej Krawczyk Feb 01 '22 at 19:25
20

You can use input.value = JSON.stringify(obj) to transform the object to a string.
And when you need it back you can use obj = JSON.parse(input.value)

The JSON object is available on modern browsers or you can use the json2.js library from json.org

Mic
  • 24,812
  • 9
  • 57
  • 70
19

You can store it in a hidden field, OR store it in a javascript object (my preference) as the likely access will be via javascript.

NOTE: since you have an array, this would then be accessed as myvariable[0] for the first element (as you have it).

EDIT show example:

clip...
            success: function(msg)
            {
                LoadProviders(msg);
            },
...

var myvariable ="";

function LoadProviders(jdata)
{
  myvariable = jdata;
};
alert(myvariable[0].id);// shows "15aea3fa" in the alert

EDIT: Created this page:http://jsfiddle.net/GNyQn/ to demonstrate the above. This example makes the assumption that you have already properly returned your named string values in the array and simply need to store it per OP question. In the example, I also put the values of the first array returned (per OP example) into a div as text.

I am not sure why this has been viewed as "complex" as I see no simpler way to handle these strings in this array.

Mark Schultheiss
  • 32,614
  • 12
  • 69
  • 100
  • odd no comments on the down votes to a viable solution. Obviously you can also put the value in a hidden field with something like $(myfieldselector).val(myvalue); as well. Both of which I noted. The array is the reason I chose the Javascript Object. – Mark Schultheiss Aug 12 '10 at 12:43
  • JS is front end, and JSP is server. What if you want to set json server side only as they will not be accesible in front end? So how will u store JSON in hidden fields? – user2696258 Aug 05 '17 at 04:09
  • @user2696258 - another question, please post that as a new question, reference this one if you find it might help with your new one, along with the code you have attempted. – Mark Schultheiss Aug 06 '17 at 02:30
16

If you use the JSON Serializer, you can simply store your object in string format as such

myHiddenText.value = JSON.stringify( myObject );

You can then get the value back with

myObject = JSON.parse( myHiddenText.value );

However, if you're not going to pass this value across page submits, it might be easier for you, and you'll save yourself a lot of serialization, if you just tuck it away as a global javascript variable.

David Hedlund
  • 128,221
  • 31
  • 203
  • 222
0

just set the hidden field with javascript :

document.getElementById('elementId').value = 'whatever';

or do I miss something?

Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
JohnSmith
  • 4,538
  • 9
  • 25
  • 25
0

It looks like the return value is in an array? That's somewhat strange... and also be aware that certain browsers will allow that to be parsed from a cross-domain request (which isn't true when you have a top-level JSON object).

Anyway, if that is an array wrapper, you'll want something like this:

$('#my-hidden-field').val(theObject[0].id);

You can later retrieve it through a simple .val() call on the same field. This honestly looks kind of strange though. The hidden field won't persist across page requests, so why don't you just keep it in your own (pseudo-namespaced) value bucket? E.g.,

$MyNamespace = $MyNamespace || {};
$MyNamespace.myKey = theObject;

This will make it available to you from anywhere, without any hacky input field management. It's also a lot more efficient than doing DOM modification for simple value storage.

jmar777
  • 38,796
  • 11
  • 66
  • 64
  • Would this method work even after asynchronous requests and could be accessed from dynamically generated elements? e.g. LoadRemoteDataFunction(...).then( save to pseudobucket) ---> DynamicallyGenerateFormPugin( Access data fetched asynchronously); – Alfie Robles Jan 30 '20 at 04:06
0

base64 solution

// encode
theInput.value = btoa(JSON.stringify({ test: true }));

// decode
let decoded = JSON.parse(atob(theInput.value));

Why base64?

The input field may be processed by a backend that runs in a different programming language than JavaScript. For instance, in PHP, rawurlencode implementation is slightly different from JavaScript encodeURIComponent. By encoding it in base64, you are sure that whatever other programming language runs on the backend, it will process it as expected.

Maciej Krawczyk
  • 14,825
  • 5
  • 55
  • 67
  • IDE's may give deprecation warnings for `btoa`/`atob`, however this is only relevant for back-end contexts (ie NodeJS). For front-end you can still use them, and to get rid of any deprecation warnings, prepend "window.", like so: `window.btoa()` or `window.atob()`... which is clearer semantic code anyhow. – Kalnode Apr 21 '22 at 17:28