0

I have a javascript question. What the best way of writing the following Javascript code dynamically. Keep in mind that I have to write the code using php echo tags. So the browser can translate it a JavaScript. Thanks

  var one = {
    info: { name: "John" }
   };

  var two = {
    info: { name: "Henry" }
  };

  var simple_config = [ one,two ];

//SOLUTION

<script>
var page = <?php  echo json_encode($tree_data->result_array()); ?> 
<?php 
 var $page_data =  echo json_encode($tree_data->result_array()); // assoc array from database

foreach ($page as $row){

 echo 'var $row['student_number'] = {
           text: { name: "Name" }
            };';

echo " var class = [];";

echo "class.push($row['student']);";


}?>
</script>

<script>
     new ClassRegistry(simple_chart_config); //pre-defined custom function
</script>
3
  • Print javascript based values with PHP. Commented Feb 6, 2017 at 22:50
  • Should henry be in var two? Commented Feb 6, 2017 at 22:50
  • 1
    Use json_encode() in PHP to convert a PHP array into a Javascript literal. Don't bother with the variables. Commented Feb 6, 2017 at 22:51

1 Answer 1

0

json_encode would do the trick. However if you still want to do it your way, you can use code below as starting point.

Something like that would do it.

$myArr = ['name' => 'Test'];
print "var one = {"; //Variable declaration
foreach ($myArr as $k => $v) {
    print $k . ': "' . $v . '",'; //All the keys and values
}
print "};"  //Close brackets

This would print:

var one = {name: "Test",};
Sign up to request clarification or add additional context in comments.

1 Comment

I dont think I explained what I was trying to accomplished correctly....II have posted a solution my original post.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.