2

In the DB, 'imgs_urls' field:

["http://localhost/wordpress-gallery/wp-content/uploads/2015/01/120.jpg","http://localhost/wordpress-gallery/wp-content/uploads/2015/01/222.jpg"]

php:

$images_urls = get_post_meta($user_post, 'imgs_urls', false); //return array
$a = json_encode($images_urls);

<input type="hidden" name="<?php echo $id; ?>urls" id="<?php echo $id; ?>urls" value="<?php echo $a; ?>" />

and now the big crap output when the page load:

enter image description here

Obviously, after in my js, I have an error when Im trying to do:

var images = $.parseJSON($("#"+imgId+"urls").val());

edit

Now if I start with the js in a function that is executed when the page is loaded:

var vv = [];
vv.push('http://localhost/wordpress-gallery/wp-content/uploads/2015/01/118.jpg');   
vv.push('http://localhost/wordpress-gallery/wp-content/uploads/2015/01/118.jpg');
$("#" + imgId + "urls").val(JSON.stringify(vv));

after the post is saved, in the DB:

["http://localhost/wordpress-gallery/wp-content/uploads/2015/01/118.jpg","http://localhost/wordpress-gallery/wp-content/uploads/2015/01/118.jpg"]

exactly the same DB format and this time no error message with:

var images = $.parseJSON($("#"+imgId+"urls").val());

I'm using the same php json_encode function...weird, any idea?

1 Answer 1

1

The problem is the quotes. One thing you can do is take the HTML version of the JSON:

$a = htmlspecialchars(json_encode($images_urls));

//JavaScript:
var images = $.parseJSON($("<div/>").html($("#"+imgId+"urls").val()).text());

Explanation:

$("<div/>").html($("#"+imgId+"urls").val()).text()

This is to get rid of the HTML entities (i.e. $lt) in $("#"+imgId+"urls").val() that we got from htmlspecialchars. We only want to parse that when parsing the JSON.

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

5 Comments

I'm still having the parse error but at least the output is much better: value="["[\"http:\/\/localhost\/wordpress-gallery\/wp-content\/uploads\/2015\/01\/122.jpg\",\"http:\/\/localhost\/wordpress-gallery\/wp-content\/uploads\/2015\/01\/224.jpg\"]"]" .I dont need the decodeURI function, all I want to do is to put each url string in the html image source tag...
@Frank Reload the page, I was wrong about decodeURI (I misread the documentation). Try the new method.
this is suppose to be straight foward...look at the edit part, thanks by the way
@Frank You set the div's value, you didn't add it as an attribute. In that case, the fact that there are quotes won't matter.
ok but did you try your code? That does not work for me, have you a jsfiddle example?

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.