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.
1 Answer 1
Trying to follow your mathematical loop conditions makes my eyes go crossed in a hurry.
Perhaps you'd entertain a less-math-heavy alternative:
foreach (array_chunk($array, 4) as $row) {
echo '<tr><td>' , implode('</td><td>', $row) , '</td>' , str_repeat('<td></td>', 4-count($row)) , '</tr>';
}
Granted this will be making a no-output call of str_repeat()
on all rows except potentially the final row, but I think this technique will be more developer friendly. I'm assuming that I understand your $data
(Demo). I could have written a conditional for str_repeat()
but felt that would only bloat the code.
I tend to lean toward passing json back from an ajax call, but for this situation sending back html is the simpler approach.
-
\$\begingroup\$ Thanks. Can you please expand your answer and show me how to pass JSON back in my case? \$\endgroup\$tera_789– tera_7892019年03月31日 19:12:55 +00:00Commented Mar 31, 2019 at 19:12
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\$