so I have very little experience in javascript, jquery or ajax but it seems I need all these things to accomplish what I want to do.
I have a website that gets a full body replacement every minute. within the body is a single html5 audio tag like this:
<audio id='sound'>
<source src="test.mp3" type="audio/mpeg">
</audio>
once the full body gets refreshed via the jquery, ajax script below I want to play that audio tag.
so I thought I set 2 functions, 1 which reloads the site and 1 which plays the sound. However this doesnt work as ajax is asynchronous. the sound gets played before a refresh.
I have been reading and it seems I need callbacks to do what I want. But through the soup of me having little knowledge of either javascript, jquery and ajax I am just lost..
I have to use a refresh like this because I don`t want to ever end in a site not found or something like that because of a connection error.
Also it seems to me that my full body replacement could use some work as using a regex like that seems rather excessive.
the last connect block is just a small colored block where I can see what was the last state of the website.
<script type="text/javascript">
function update_site() {
$.ajax({
url: "/test",
dataType: "html",
cache: false,
success: function(data) {
// Replace body with loaded site. You can do more checks here to check
// if the fetched content is all there.
var body_html = data.replace(/^[\S\s]*<body[^>]*?>/i, "")
.replace(/<\/body[\S\s]*$/i, "");
$('body').html(body_html);
$('.last_connect').css('background-color', 'blue');
},
error: function(data) {
$('.last_connect').css('background-color', 'red');
}
});
}
function play_snd() {
$('.last_connect').css('background-color', 'yellow');
$('#sound').trigger("play");
}
// Run every 20 secs.
window.setInterval(function() {
update_site();
play_snd();
}, 4000);
</script>