Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
/////
// remember that this two are two different files
/////
/////
// the main file that calls the backend
/////
<html>
<head>
<title>
<?php
echo 'title';
?>
</title>
</head>
<body onload="ClearInputs()">
<label for="cols">rows:</label>
<input type="text" id="cols" name="cols" onkeyup="SetCols(this.value)" onload="this.value=''">
<label for="rows">cols:</label>
<input type="text" id="rows" name="rows" onkeyup="SetRows(this.value)">
<span id="out"></span>
</body>
<script>
let cols = '';
let rows = '';
let script = '';
let output = document.getElementById("out");
let ajax = new XMLHttpRequest();
ajax.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
output.innerHTML = this.responseText;
}
}
function CreateTable() {
script = 'make_ajax_table.php?' + cols + '&' + rows;
// console.log(script);
ajax.open('GET', script, true);
ajax.send();
}
function SetCols(ncols) {
cols = 'cols=' + ncols;
if (rows != '') {
CreateTable();
}
}
function SetRows(nrows) {
rows = 'rows=' + nrows;
if (cols != '') {
CreateTable();
}
}
function ClearInputs() {
document.getElementById("cols").value = '';
document.getElementById("rows").value = '';
}
</script>
</html>
/////
// the php file that creats the actual table
// name is: create_ajax_table.php
/////
<?php
$cols = $_REQUEST['cols'];
$rows = $_REQUEST['rows'];
// in this case the try-catch-finally block
// is useless because the everything that the
// user can input would become either a valid
// integer or 0. Remains that we never know what could happen
try {
$cols = (int)$cols;
$rows = (int)$rows;
}
catch (exception $e) {
echo 'hi, something strange happened. <br> Let the developers know of this error ' . $e;
}
finally {
echo '<table border=1>';
for($i = 1; $i < $cols+1; $i++)
{
echo '<tr>';
for ($j = 1; $j < $rows+1; $j++)
{
echo '<td>' . $j * $i . '</td>';
}
echo '</tr>';
}
echo '</table>';
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment