1

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?

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Dennis Ngu
  • 37
  • 4
  • 1
    I do not understand, how you can "pass" something from PHP to JavaScript? Is this done by AJAX or simple `=…?>`text replacement? – Uwe Keim Oct 29 '19 at 05:18
  • make sure your php value are converted to javascript value, you only can `$decoded['method']` – FeelRightz Oct 29 '19 at 05:19
  • 1
    This may help : https://www.codexworld.com/how-to/convert-php-array-to-javascript-array/ – tyb9900 Oct 29 '19 at 05:20
  • @UweKeim the php array will be passed to the another javaScript file by using curl. So the data will pass as well. – Dennis Ngu Oct 29 '19 at 05:20
  • Possible duplicate of [Convert php array to Javascript](https://stackoverflow.com/questions/5618925/convert-php-array-to-javascript) – LF00 Oct 29 '19 at 06:03

2 Answers2

1
<?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.

Avinash Dalvi
  • 8,551
  • 7
  • 27
  • 53
0

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);
}
Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Alok Mali
  • 2,821
  • 2
  • 16
  • 32