I have two files. The first is my front page that gets information via an ajax function and the second one is a PHP file that gets the data from a database.
The data returned is a string, formatted as an array (example : ['0','0','0','0','0','0','0','0','0','0'] ).
I need the PHP data to be interpreted as a JS array so I can use it easily.
I tried to return a PHP array, but the result in JS is undefined.
Here is my code :
PHP data retriever :
$g = new Game();
$top1 = ($g->getMatchKills($lobby)[0]['p1c1kills']);
$top2 = ($g->getMatchKills($lobby)[0]['p2c1kills']);
$jgl1 = ($g->getMatchKills($lobby)[0]['p1c2kills']);
$jgl2 = ($g->getMatchKills($lobby)[0]['p2c2kills']);
$mid1 = ($g->getMatchKills($lobby)[0]['p1c3kills']);
$mid2 = ($g->getMatchKills($lobby)[0]['p2c3kills']);
$adc1 = ($g->getMatchKills($lobby)[0]['p1c4kills']);
$adc2 = ($g->getMatchKills($lobby)[0]['p2c4kills']);
$sup1 = ($g->getMatchKills($lobby)[0]['p1c5kills']);
$sup2 = ($g->getMatchKills($lobby)[0]['p2c5kills']);
echo "['" . $top1 ."','" .$top2. "','" . $jgl1 . "','" . $jgl2 . "','" . $mid1 . "','" . $mid2 . "','" . $adc1 . "','" . $adc2 . "','" . $sup1 . "','" . $sup2 . "']";
And my JS script is :
function RefreshKDAs() {
$.ajax({
url: 'getKills.php?lobby=<?= $lobby ?>',
success: function (data) {
console.log(data)
}
})
}
CodePudding user response:
Use json_encode
to format a PHP array into JSON:
https://www.php.net/manual/en/function.json-encode.php
CodePudding user response:
$vartopass=json_encode($arraytopass);
js
var arr= <?=$vartopass?>;
console.log(arr)