1

So, I have to parse an php json into javascript.

The code looks like this:

$thumbnails = [];
foreach ($images as $key => $image) 
{
  $thumbnails[$image->time] = [
    'src' => MovieEntity::getImageWithPublicPath(
      $movie->id, $image->filename, 130, 0, false
    ),
    'width' => '165px',
    'height' => '95px'
  ];
}

return json_encode($thumbnails, JSON_UNESCAPED_SLASHES);

and the result is:

{"5":{"src":"google.ro","width":"165px","height":"95px"},"7":

I want to take the src, width and height and insert them as pictures like:

<a href="">
  <img src="src of image" width="" height="">
</a>

What do I need to do? This variable in PHP is called $thumbnails, which returns the JSON I showed above.

<?php echo $thumbnails ?>

LE: My solution is:

<?= '<script>var json='.$thumbnails.'</script>' ?>
console.log(json);

This will return you the json in the console.

3 Answers3

0

If you're using jQuery: $.parseJSON().

If you're using plain javascript: JSON.parse()

// jQuery snipet
var thumbnails = $.parseJSON('<?php echo $thumbnails; ?>');
console.log(thumbnails.src);
console.log(thumbnails.width);
console.log(thumbnails.height);
Dacklf
  • 700
  • 4
  • 15
  • If I try to use your code I got this: Uncaught SyntaxError: Unexpected token < in JSON at position 0 –  Oct 20 '17 at 08:01
  • @StefanIordache there was a typo: I have written $thumnails instead of $thumbnails. Try it now – Dacklf Oct 20 '17 at 08:13
  • Yea, I saw it from the beginning. I still got this message from console. Uncaught SyntaxError: Unexpected token < in JSON at position 0 at JSON.parse () at Function.oe.parseJSON –  Oct 20 '17 at 08:31
  • @StefanIordache can I see what does it print your javascript code when you echo $thumbnails? try console.log('') and let me see if the JSON is correct – Dacklf Oct 20 '17 at 09:02
  • I get the string between the quotes –  Oct 20 '17 at 09:13
  • I tryed something different = '' ?> and when I call 'json' in console log it returns me the json –  Oct 20 '17 at 09:13
0

You can do this in plain JavaScript.

Echo the JSON into a script tag

<script type="application/json" id="json">
    <?php echo $thumbnails; ?>
</script>

Then target it with JavaScript

var json = JSON.parse(document.getElementById('json').innerHTML);

var img = document.querySelector('img');

img.src = json.src;
img.width = json.width;
img.height = json.height;
0

In your javascript, you have to request your php function by doing a get request (assume you use jQuery). After that, in the success callback, you have the data. So try something like that :

$.ajax({
   url : 'file.php', // your php file
   type : 'GET', // type of the HTTP request
   success : function(data){
      var obj = jQuery.parseJSON(data);
      console.log(obj);
   }
});

You can go here for more informations

Berserk
  • 821
  • 12
  • 23