Looking to update my website dynamically based on a value from the MySQL database in real-time. I currently have some code that partially achieves this functionality, but it seems to fail after a few calls by randomly switching between two values.
I have three PHP pages - one retrieves data from the database (database.php) and two generate responses based on the data (response1.php and response2.php). I verified that these pages return the correct values. The issue likely lies within my main HTML page below. I'm uncertain if the approach I've taken is optimal or if there's a better solution.
<html>
<head>
<script type="text/javascript">
var databaseanswer, xmlhttp;
function databasecheck() {
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "database.php", true);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
databaseanswer = xmlhttp.responseText;
document.getElementById("database").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.send();
}
function response() {
if (databaseanswer == "No Tag") {
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "response1.php", true);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("response").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.send();
}
else {
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "response2.php", true);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("response").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.send();
}
}
setInterval(databasecheck, 1800);
setInterval(response, 2000);
</script>
</head>
<body>
<p> This is just a test site </p>
<p> Response from server: </p>
<div id="response">
</div>
<p> Answer from database: </p>
<div id="database">
</div>
</body>
</html>
Here's an updated version of my code:
<html>
<head>
<script>
function database(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET","responsedatabase.php",false);
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("database").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.send();
}
setInterval(database,1000);
</script>
</head>
<body>
<p> Answer from database: </p><div id="database"></div>
</body>
</html>