store return json value in input hidden field

JavascriptJqueryJson

Javascript Problem Overview


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

Javascript Solutions


Solution 1 - Javascript

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"}

Solution 2 - Javascript

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

Solution 3 - Javascript

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.

Solution 4 - Javascript

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.

Solution 5 - Javascript

just set the hidden field with javascript :

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

or do I miss something?

Solution 6 - Javascript

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.

Solution 7 - Javascript

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionhershView Question on Stackoverflow
Solution 1 - JavascriptroduView Answer on Stackoverflow
Solution 2 - JavascriptMicView Answer on Stackoverflow
Solution 3 - JavascriptMark SchultheissView Answer on Stackoverflow
Solution 4 - JavascriptDavid HedlundView Answer on Stackoverflow
Solution 5 - JavascriptJohnSmithView Answer on Stackoverflow
Solution 6 - Javascriptjmar777View Answer on Stackoverflow
Solution 7 - JavascriptMaciej KrawczykView Answer on Stackoverflow