3

Hi Im trying to send an array from php to my javascript. Is this possible? Ive tryied a few examples that Ive found but non of them have worked.

Here is what Im trying to do:

php file:

<?php
$n = array('test','test2', 'test3');
<script type='text/javascript'> 
    initArray($n);
</script>
?>

javascipt:

function initArray(array){
    for(var i = 0; i < array.length; i++){
        alert(array[i]);
    }
}

Thx for all your answers

2 Answers 2

5
<?php 
$n = array('test','test2', 'test3'); 
?>
<script type="text/javascript"> 
    var arr = <?php echo json_encode($n); ?>; // create the JavaScript array
    initArray(arr); // use it
    function initArray(array){
        for(var i = 0; i < array.length; i++){
            alert(array[i]);
        }
    }
</script>

You need to use json_encode to convert a PHP array to a JavaScript one, and output its result while assigning it to a JavaScript variable.

1
  • @Linqan: Great! If my answer solved your problem, feel free to accept it by clicking the empty tick below the vote counts on the left side of my answer to make it green, which will mark your question as resolved. Commented Aug 11, 2011 at 9:28
3

You have to serialize it. Try it with JSON. http://php.net/manual/en/book.json.php

2
  • Ive never used JSON. Is that the only way? Commented Aug 11, 2011 at 9:14
  • Not the only, but I guess is the best. Take a look at this example. php.net/manual/en/function.json-encode.php Commented Aug 11, 2011 at 9:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.