I would like to know if this code follows recommended practices and standards for AJAX/PHP calls. Can this AJAX + PHP code be improved in terms of security, performance, etc.?
ajax.js:
function getTableData() {
const xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
document.querySelector('#test-table tbody').innerHTML = this.responseText;
}
}
xmlhttp.open('GET', 'ajax.php', true);
xmlhttp.send();
}
$(document).ready(function () {
getTableData();
});
ajax.php:
<?php
$data = prepareDataForTable();
$data_length = count($data);
$columns = 4;
for ($row = 0; $row < $data_length; $row += $columns) {
echo '<tr>';
for ($col = 0; $col < $columns && ($col + $row) < $data_length; $col++) {
echo '<td>' . $data[$col + $row] . '</td>';
}
echo '</tr>';
}
?>
ajax.html:
<table id="test-table">
<tbody>
</tbody>
</table>
I specifically want to know if this is a good way to send information back to the client - by running loops and echoing output.
prepareDataForTable()
would return a 2D data array you could use 2 simpleforeach
loops to echo the table. That would even be more flexible than what you have now. \$\endgroup\$prepareDataForTable()
actually returns 1D array but I need to print<tr>
tags for every 4th element in array so I thoughtfor
loop was a better choice here. If you can demonstrate how to do the same withforeach
, then I'll appreciate it. \$\endgroup\$prepareDataForTable()
return a 1D array of 2D data. Returning a 2D array will make it easier to handle the data. \$\endgroup\$