Dennis Ngu
Dennis Ngu

Reputation: 37

How to get value from a PHP array in JavaScript?

Let's say we have one PHP array:

$decoded = array(
    'method' => 'getFile',
    'number' => '12345'
);

The array data will pass to another JavaScript get function(params).

function get(params) {
}

How I get the $decoded['method'] value in JavaScript language in the get function?

Upvotes: 1

Views: 133

Answers (2)

Alok Mali
Alok Mali

Reputation: 2881

Javascript array and PHP arrays are not equal. But the objects of both languages are equal. Then you can JSON encode your array in PHP and pass the encoded value in the javascript.

For example:

In PHP

<?php 
   $decoded = array(
      'method' => 'getFile',
      'number' => '12345'
   );
?>

In JS

var params = <?php echo json_encode($decoded); ?>;
function get(params) {
   console.log('method', params.method);
   console.log('number', params.number);
}

Upvotes: 0

Avinash Dalvi
Avinash Dalvi

Reputation: 9301

<?php

$decoded = array(
'method' => 'getFile',
'number' => '12345'
);

?>
<script>
var params =  <?php echo json_encode($decoded); ?>;
get(params);
function get(params){
    console.log(params);
    console.log(params['method']);
}
</script>

Use this way. you have to get php variable or array inside javascript by printing or echo. Then you can call function.

Upvotes: 1

Related Questions