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?

5
  • 1
    I do not understand, how you can "pass" something from PHP to JavaScript? Is this done by AJAX or simple <?=…?>text replacement? Commented Oct 29, 2019 at 5:18
  • make sure your php value are converted to javascript value, you only can $decoded['method'] Commented Oct 29, 2019 at 5:19
  • 1
    This may help : codexworld.com/how-to/convert-php-array-to-javascript-array Commented Oct 29, 2019 at 5:20
  • @UweKeim the php array will be passed to the another javaScript file by using curl. So the data will pass as well. Commented Oct 29, 2019 at 5:20
  • Possible duplicate of Convert php array to Javascript Commented Oct 29, 2019 at 6:03

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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);
}

Comments

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.