2

I have a PHP file with an Array ($phpArray) in it and I am trying to pass it through a function in a JS File (data.js). I can figure out how to do it. Any suggestions?

dataInput.php (PHP File)

<?PHP
 $phpArray=[[1,2,3,4,5],
           [2,3,5,6,7]];
?>

data.js (JS File)

function getRaceResults1(){
    phpArray[] -> jsArray[];
    return jsArray;
}
Smurfitchy
  • 21
  • 1

2 Answers2

2

PHP provides a function to convert PHP arrays into Javascript code: json_encode().

It's JSON format, JSON stands for JavaScript Object Notation.

Here is how to solve my problem:

dataInput.php (PHP File)

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>

<?php $phpArray=[[1,2,3,4,5], [2,3,5,6,7]]; ?>
<script>
    <?php echo 'var jsArray = ' . htmlspecialchars(json_encode($phpArray)) . ';'; ?>
</script>

</body>
</html>
Lam Tran Duc
  • 588
  • 6
  • 16
  • Hey Lam, thanks for the help. I am confused, maybe I am reading it incorrectly. The PHP array is in a PHP file and I want to put it in a JS file to use the array there – Smurfitchy Nov 29 '21 at 02:57
  • @Smurfitchy Putting PHP arrays in a js file is a big no-no. If you want to use that array, then just embed your js file below the code – Lam Tran Duc Nov 29 '21 at 03:07
  • From Lam's answer @Smurfitchy you just add `` after end of `` of the `var jsArray = '...';`. To Access `jsArray`, use `JSON.parse()`. [See more](https://www.w3schools.com/js/js_json_objects.asp) – vee Nov 29 '21 at 03:29
0

api.php

echo json_encode([[1,2,3,4,5], [2,3,5,6,7]]);

ajax.js

fetch("./api.php")
    .then(res => res.json()})
    .then(data => {
          // data is array
     })

You can try ajax,

WangZhen
  • 37
  • 1