0

I have found these two ways:

1st way (width incorrect)

<?php
    $arr = new Array (...);
?>

<input id="arr" value="<?php echo json_encode($arr); ?>" hidden>

<script>
    $(function (){
      var arr = $("#arr").val(); // array with trash
    });
</script>

2nd (we need control sequence)

<?php
    $arrJS = json_encode($arr);
?>

<script>
    var arrJS = <?php echo $arrJS; ?>;  // good array
</script>

Question: Is there a better attempt?

bytecode77
  • 14,163
  • 30
  • 110
  • 141
  • 1
    Have you looked into ajax? – Daan Mar 20 '15 at 08:29
  • Ajax would be a terrible solution to the problem. It adds an extra HTTP request. – Quentin Mar 20 '15 at 09:47
  • What does "width incorrect" mean? What does "we need control sequence" mean? What is your actual problem? This looks like you have found two methods, and one is broken and the other works, and you are asking for a code review (which is off-topic for Stackoverflow). – Quentin Mar 20 '15 at 09:49

1 Answers1

0

Have you considered using AJAX? Here's an example: Javascript:

$.ajax( "example.php" )
.done(function(json) {
 var jsObject = json;
})

and in your 'example.php' file:

<?php 
 $arr = new Array ('element1'=>'value1', 'element2'=>'value2');
 header("Content-type: text/json");

 echo json_encode($arr);
 exit;
?>
NaijaProgrammer
  • 2,892
  • 2
  • 24
  • 33
  • Ajax is an awful solution to this problem. It adds a new HTTP request and requires asynchronous handling. You've also got it wrong, the [content type for JSON is `application/json` not `text/json`](http://stackoverflow.com/questions/477816/what-is-the-correct-json-content-type). – Quentin Mar 20 '15 at 09:50