52

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();
1

7 Answers 7

162

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"}
Sign up to request clarification or add additional context in comments.

8 Comments

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).
Best solution so far, this should be accepted answer.
Wow best solution I've a problem with JSON.stringify for 2 hours then I found this mind blow answer. Thank you.
Worked for me when using an input element, but not when using a div. Great solution.
I used JSON.stringify() but the value did not appear on the input element. But I can work with this now, awesome solution.
|
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

Comments

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.

3 Comments

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.
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 - 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.
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.

Comments

1

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.

1 Comment

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.
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.

1 Comment

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);
0

just set the hidden field with javascript :

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

or do I miss something?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.