CMArg
CMArg

Reputation: 1567

quotes in php array to javascript array

I want to pass a php array to javascript. I've tried several examples taken form this site, but the rest of my code seem not to recognize them. I think the problem is in the quotes or format of the array.

First: var functionlist defined as below works OK.

<script type="text/javascript">
    var functionlist = Array('1','2','3','4','5','6','7','8','9','10','11','12');
    //Rest of the code
</script>

Second: var functionlist defined as below works OK.

<script type="text/javascript">
    var functionlist=Array("1","2","3","4","5","6","7","8","9","10","11","12");
    //Rest of the code
</script>

But the code below is not working, despite the fact that echoing $TransfArray renders something quite similar to the above.

<?php
    for ($i = 0; $i <= 12; $i++) {
        $OriginalArray[$i] = $i;
    }
    $TransfArray= "'" . implode("','", $OriginalArray) . "'";
?>

<script type="text/javascript">
    var functionlist = Array(<? echo $TransfArray; ?>);
    //Rest of the code
</script>

Nor does the code below

<?php
    for ($i = 0; $i <= 12; $i++) {
        $OriginalArray[$i] = $i;
    }
    $Original_to_json = json_encode($OriginalArray);
?>

<script type="text/javascript">
    var functionlist =  <?php echo $Original_to_json; ?>;
    //Rest of the code
</script>

Does anyone detect the problem? Thnaks in advance.

Upvotes: 2

Views: 658

Answers (3)

HILARUDEEN S ALLAUDEEN
HILARUDEEN S ALLAUDEEN

Reputation: 1752

Use casting as follows,

<?php
for ($i = 0; $i <= 12; $i++) {
$OriginalArray[]= (String)$i;
}
$Original_to_json=json_encode($OriginalArray);
?>

<script type="text/javascript">
var functionlist =  <?php echo $Original_to_json; ?>;
//Rest of the code
</script>

Upvotes: 2

Omar Abid
Omar Abid

Reputation: 15976

Writing JavaScript code with PHP is a terrible practice. You shouldn't be doing that. Instead, you can do something different and easy.

  1. In PHP, you generate a JSON document by converting the array to a JSON object. Use the json_encode function for that. Name your file "json.php" (though naming is data.json is probably a better practice, but you'll have to go through more steps).
  2. Now, you can include the file with in your HTML document <script src="json.php"></script> Or you can use AJAX to load it dynamically.
  3. The JSON object will have the JavaScript array.

Upvotes: 0

JoDev
JoDev

Reputation: 6873

Try this :

<script type="text/javascript">
var functionlist =  <?php echo json_encode($OriginalArray); ?>;
//Rest of the code
</script>

Enjoy ;)

Upvotes: -1

Related Questions