Store JSON in a hidden input element?

Stephen Belanger picture Stephen Belanger · Jun 30, 2010 · Viewed 11.7k times · Source

I need to be able to generate an effectively unlimited number of datasets, so what I want to do is something like this;

<input type="hidden" name="items[]" value="{id:1,name:'some-name'}" />

I tried JSON.stringify to convert my array in javascript and store it in the current hidden input element, but it wraps all the keys and values in double quotes, which obviously conflicts with HTML wrapping the entire value in double quotes. Somehow I need to escape the quotes, but I need this to work two ways...basically these elements are generated with PHP and placed in the page in order, then I can add or delete items on the user end and submit the page, which should have PHP iterating through these hidden elements and updating the records.

Anyone have any suggestions on an escaping method of some sort?

Answer

Kamil Szot picture Kamil Szot · Jun 30, 2010

You can use escaping function presented here: http://phpjs.org/functions/htmlspecialchars:426

It should escape chars in json and make your string safe to use as value of html attribute.

If you want to do the escaping on PHP then you should use function htmlspecialchars() that is built in PHP.