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

2 Answers 2

3

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>
Sign up to request clarification or add additional context in comments.

3 Comments

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 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 <script><?php echo 'var jsArray ...</script>
From Lam's answer @Smurfitchy you just add <script src="your-js-file.js"></script> after end of </script> of the var jsArray = '...';. To Access jsArray, use JSON.parse(). See more
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,

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.