0

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)
        }
    })
}
Shadow
  • 33,525
  • 10
  • 51
  • 64
skeenotihk
  • 25
  • 5
  • PHP: `$data = $->getMatchKills($lobby)[0];` and `header("Content-Type: applicaton/json");` and finally `echo json_encode($data);` also note that unless your script is part of index.php or something, it won't insert the actual $lobby value into the url. Where exactly are you getting undefined? Because that ajax request should at least be able to load the text. –  Sep 23 '21 at 20:50
  • Regarding your comment below: JSON is text, i.e. a string. But as long as the string contains valid JSON, it can be parsed by JS (jQuery) into an array/object. –  Sep 23 '21 at 20:54
  • Your first reply made the job ! Thanks a lot. I learned a lot from this, thank you. – skeenotihk Sep 23 '21 at 21:03
  • @NicoHaase Its kinda close of what I used, see below what I've used. But thanks for the help ! – skeenotihk Sep 25 '21 at 20:52

2 Answers2

2

Use json_encode to format a PHP array into JSON:

https://www.php.net/manual/en/function.json-encode.php

Aran
  • 2,429
  • 1
  • 19
  • 19
0

I solved this using

$data = $g->getMatchKills($lobby)[0];
header("Content-Type: applicaton/json");
echo json_encode($data);

on my data retriever PHP file.

Thanks to Chris G.

skeenotihk
  • 25
  • 5