Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store JSON in a hidden input element?

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?

like image 293
Stephen Belanger Avatar asked Jun 29 '10 22:06

Stephen Belanger


1 Answers

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.

like image 59
Kamil Szot Avatar answered Oct 27 '22 14:10

Kamil Szot