PerfectGohan
PerfectGohan

Reputation: 47

How to print JSON array inside script tag?

I'm trying to display JSON array inside <script> tag, is that possible?

Here is what I've tried so far:

<script>
    var x =  JSON.stringify(data);

var json = (function() {
        var json = null;
        $.ajax({
            'async': false,
            'global': false,
            'url': "empdata.json",
            'dataType': "json",
            'success': function (data) {
                json = data;
            }
        });
        return json;
    })();
 </script>

What I'm trying to do:

<script>

var videos = {"employee_id":"1","employee_name":"Steve","designation":"VP","hired_date":"2013-08-01","salary"
:"6000"};

</script>

Upvotes: 2

Views: 1104

Answers (1)

ArtisticPhoenix
ArtisticPhoenix

Reputation: 21661

Yea you just echo it like this, assuming you have an $array of parameters like array("employee_id"=>1 ... )

var videos = <?php echo json_encode(array(
    "employee_id"=>1
)); ?>;  // <- don't miss the java-script semi-colon though

This should just print

  var videos = {"employee_id":1};

PHP doesn't care where you echo it at, in your page, it doesn't have a concept about what a <script> tag is. All it knows is some things are php code, everything else is string content.

OR you could just do this

  var videos = <?php echo '{"employee_id":1}'; ?>;

But that is kind of pointless, unless you mean like this.

  var videos = <?php echo '{"employee_id":'.$employee_id.'}'; ?>;

Or you can do this way to

   var videos = {"employee_id":1};

And just put it in there, I don't understand anymore?

If you mean from a file containing your json, then sure.

<?php
 $json = file_get_contents( 'pathtofile.json');
?>

<script> ... etc.\

 var videos = <?php echo $json; ?>;

PHP can read files, and it can echo the contents of those files, PHP doesn't care whats in them. The only catch is the content has to be valid Json for the javascript to work. But php doesn't care if it's JSON, XML, Binary etc. it's all text because PHP is a loosely typed language. In fact php doesn't care if your Javascript works, it has no concept of what javascript is.

In fact this works too ( assuming image.jpg is a real image file. ).

  $jpg = file_get_contents( 'image.jpg' );
  echo '<img src="'. $jpg.'" \>

OR

   header('Content-Type: image/jpeg');
   echo file_get_contents( 'image.jpg' );  //assuming there is no other content

Upvotes: 2

Related Questions