I'm using PHP to populate an HTML table with random numbers on page load. When button is clicked, I want to re-populate the table with new numbers by calling PHP via an ajax request. Problem is I can't use (or at least really want to avoid using) external files : PHP must be called via ajax request in the same file.
File is index.php and contains following simplified PHP code :
<?php
//code to be executed via ajax call should be placed here ?
?>
<!DOCTYPE html>
<HTML>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width">
<HEAD>
<title>PHP test</title>
</HEAD>
<BODY>
<table id="table">
<?php //problem : only works once in page load
$howMany = 10;
$values = array();
echo '<tr>';
for ($v = 0; $v < $howMany; $v++) {
$values[$v] = mt_rand(-10, 10);
echo '<td>'. $values[$v] .'</td>';
}
echo '</tr>';
?>
</table>
<button id="btn">Generate new numbers</button>
<BODY>
Here is my current ajax request :
<script type="text/javascript">
function send_ajax() {
console.log('btn clicked');
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest(); //code for IE7+, Firefox, Chrome, Opera, Safari
}
else {
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP'); //code for IE6, IE5
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log('data sent');
}
}
xmlhttp.open('POST', 'index.php', true);
//xmlhttp.send(document.getElementById('input').value);
}
document.getElementById('btn').addEventListener('click', send_ajax, false);
</script>
I'm sure I'm missing something obvious, but I have no idea how I should adapt my php code and ajax request to repopulate the table when receiving ajax call in the same file.
(Note : I know it would be very easy using external files, but this scenario is a typical example of what I need to do with ajax and PHP for more complex tasks over dozens of different files).