I am cracking my head over this now for two days… Frustrating. I have a html page which contains divs who get their value from a JS on the page. I am running a loop to refresh them but: Nothing happens. So I am a JS beginner but: Console doesn’t give me an error. jsFiddle says my loop code is ok… WHAT AM I MISSING????
var delay = 1000;
function loop() {
$.get("http://www.starhit1fm.com/Friday.html")
.done(function(r) {
var newDom = $(r);
$('#imgContainer').replaceWith($('#imgContainer', newDom));
$('#status').replaceWith($('#status', newDom));
$('#showon').replaceWith($('#pshowon', newDom));
});
if (time >= 0 && time <= 4) {
imgElement.src = "https://www.starhit1fm.com/images/covers/nonstop1.jpg";
imgEeight = 70;
imgElement.width = 70;
// the image to a container div
var container = document.getElementById("imageContainer");
container.appendChild(imgElement);
var showstatus = "- - - - - Y O U A R E L I S T E N I N G T O - - - - -";
document.getElementById("status").innerHTML = showstatus;
var actshow = " Music Non Stop<br> We get you through the night!"
document.getElementById("showon").innerHTML = actshow;
}
}
setInterval(loop, delay);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<div align="center">
<table cellspacing="2" cellpadding="2">
<tr>
<td colspan="2" align="center">
<font face="Verdana" size="3" color="#FF0000"><b><span class="blinking" id="status"></span></b></font>
</td>
</tr>
<tr>
<td>
<div id="time"></div>
<div id="imageContainer"></div>
</td>
<td valign="middle">
<div>
<span style="font-family: Verdana; font-size: 20px;">
<b> <span id="showon"></span></b>
</span>
</div>
</td>
</tr>
</table>
</div>
This code is supposed to refresh DIV tags or IDs on my html page. I just don’t know anymore where my problem is…. The code is on the same page where the JS is with the if else loops.
You can check the page at www.starhit1fm.com/Friday.html
2
Answers
The console shows:
So the problem is you need change
to
AJAX is asynchronous, so your code that updates the DIVs based on the time is running before the AJAX completes. Then the
.done()
function overwrites them with the empty DIVs from the server.You should move that code into the
.done()
function, so you first refresh from the server, then modify it based on the time.You should also update the
time
variable each time the loop runs, so the content changes when the time of day changes.