I’m struggling to send a multidimensional PHP array to JavaScript using Ajax. New PHP and JavaScript samples are provided, but the response isn’t parsed properly.
// sample_data.php
$dataList = [];
for ($i = 0; $i < 5; $i++) {
$dataList[$i] = [
'username' => 'User' . $i,
'contact' => '555-01' . $i
];
}
header('Content-Type: application/json');
echo json_encode($dataList);
var xhrRequest = new XMLHttpRequest();
xhrRequest.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
const result = JSON.parse(this.responseText);
console.log(result);
}
};
xhrRequest.open('GET', 'sample_data.php', true);
xhrRequest.send();