0

I'm building a website that store json data to hidden input element with php

<input type='hidden' class='json_data' name='json_data' value='".json_encode($data[0])."'>

with that code, I have this result:

<input class="json_data" type="hidden" value="[{"ALBUM_ID":"1234","PHOTOS_ID":"1234578"}]" name="json_data">

but when I try to get the value with jquery.val and trying to show ALBUM_ID, i get this {

anything wrong with my way of putting json into html correctly?

and then get it with jquery / javascript ?

thanks

4
  • 3
    May be because of " inside " Commented Aug 29, 2013 at 13:06
  • i did htmlspecialchars but still get the same result. Commented Aug 29, 2013 at 13:17
  • Why are you putting this in an hidden input and not just adding a script tag to the page with the value? Commented Aug 29, 2013 at 13:23
  • because the data will be save to the database. Commented Aug 29, 2013 at 13:35

4 Answers 4

3

First go ahead at this open console and see the result. Ctl+Shift+j.

http://jsfiddle.net/techsin/Q2MHA/

You need to do two things fix. ' and "'

Second just this code

JSON.parse($('.json_data').val())[0]

you need [0] because for some reason your json object is wrapped in []..you would know why.

Your html should look like this

<input ... value='[{"ALBUM_ID":"1234","PHOTOS_ID":"1234578"}]'...>

Sign up to request clarification or add additional context in comments.

Comments

1

You need to correctly handle entities in your input's value. If you populate it with PHP, use htmlspechalchars() and use result from this function

1 Comment

i did do that. htmlspecialchars(json_encode($data)) but still get the {
1

inspect the following line carefully.

<input class="json_data" type="hidden" value="[{"ALBUM_ID":"1234","PHOTOS_ID":"1234578"}]" name="json_data">

As you see you have used " for your string enclosement. The json string also includes " which breaks your string enclosement. Use ' to enclose the string.

<input class="json_data" type="hidden" value='[{"ALBUM_ID":"1234","PHOTOS_ID":"1234578"}]' name="json_data">

2 Comments

And when the value has a ' in it? Breaks once again!
@epascarello what if json string include ' and " both.What to do in this case ?
0

Try to escape the " with addslashes or htmlspecialchars

or encode the string with base64 and decode it with JS before parsing the string as JSON

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.