How can I transfer a two-dimensional PHP array to JavaScript via Ajax?

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();

I have found that transferring a two-dimensional PHP array to JavaScript using Ajax is relatively straightforward once the data is encoded correctly. Using json_encode in PHP guarantees the data is in the proper JSON format, especially when combined with setting the correct Content-Type header. My experience taught me to check for unexpected output, like PHP warnings or whitespace, which can break the JSON parsing in JavaScript. I recommend verifying the raw JSON output first, then using AJAX to retrieve and parse the result, ensuring a smooth transfer.