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