wordpress JSON.parse syntax error

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:

Read More
$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?

Related posts

Leave a Reply

1 comment

  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.