I have the following HTML:
<html>
<head>
<script src="results.js" type="text/javascript"></script>
<title>Results</title>
</head>
<body>
<div id="resultsDiv"></div>
</body>
</html>
The following JavaScript:
window.onload = function() {
init();
}
var xmlhttp;
var intervalHandle;
function init() {
getAjaxData();
intervalHandle = setInterval(getAjaxData, 2000);
}
function getAjaxData() {
if (window.XMLHttpRequest) {
// IE7+. Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else {
// IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = showJSONData;
xmlhttp.open("GET", "results2Json.php", true); // GET results from DB
xmlhttp.send();
}
function showJSONData() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
var data = JSON.parse(xmlhttp.responseText);
if (data.results.length > 0) { // Delete this line and it's closing brace, below, and the code does what expected
var output = '<table border=1>';
output += '<tr><th>Name</th></tr>';
for (var i = 0; i < data.results.length; i++) {
output += '<tr><td>' + data.results[i].name + '</td></tr>';
}
output += '</table>';
document.getElementById("resultsDiv").innerHTML = output;
} //Closing brace
}
}
And finally the following PHP:
<?php
$con = mysqli_connect("localhost","root","");
mysqli_select_db($con,"random");
$result = mysqli_query($con, "select name from random_name");
$rs = array();
while($rs[] = mysqli_fetch_assoc($result)) {
// do nothing ;-)
}
mysqli_close($con);
unset($rs[count($rs)-1]); //removes a null value
print("{ \"results\":" . json_encode($rs) . "}");
?>
all just pulling a single column from a DB, and automatically refreshing the results every 2 seconds. If I add to the DB, the results are refreshing fine. If I delete items from the DB all works fine also, until I attempt to delete the last item. This then remains on screen. I'm aware that if I take out the if (data.results.length > 0) line then the final item will delete OK but what I want to achieve is that the table header is not displayed either if the SQL query in the php file returns no results. Any help would be great, thanks.
echo json_encode(array('results' => $rs));so that your entire output is controlled byjson_encode