-1

When calling a PHP function (which returns array) from Javascript I can't seem to view it.

The message I get is

function Array() { [native code] }

How can I access items within the array.

When I use alert(padd[0]); the message returns undefined.

<?php

function getArray()
{
   $cars = array("Volvo", "BMW", "Toyota");
   return $cars;
}

?>

<script type="text/javascript">

function phpadd()
{
   var padd = <?php echo getArray();?>; 
   alert(padd);
}

</script>
yolenoyer
  • 8,797
  • 2
  • 27
  • 61
PaulJames
  • 95
  • 1
  • 8

1 Answers1

3

Just add json_encode() in the PHP function

<?php

function getArray()
{
    $cars = array("Volvo", "BMW", "Toyota");
    return json_encode($cars);
}
getArray();
?>

<script type="text/javascript">

function phpadd()
{
    var padd = <?php echo getArray();?>; 
    alert(padd);
}
phpadd();
</script>
Moses Schwartz
  • 2,857
  • 1
  • 20
  • 32