PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, March 6, 2022

[FIXED] Parse php json to javascript

 March 06, 2022     javascript, jquery, json, php, yii     No comments   

Issue

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.


Solution

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);


Answered By - Dacklf
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing