Skip to content

Instantly share code, notes, and snippets.

@hofmannsven
Last active May 23, 2023 18:40
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save hofmannsven/9964415 to your computer and use it in GitHub Desktop.
Save hofmannsven/9964415 to your computer and use it in GitHub Desktop.
Simple Ajax Polling Demo
<!DOCTYPE html>
<head>
<title>Ajax Polling</title>
<meta charset="UTF-8" />
</head>
<body>
<p>Status: <span class="status"></span></p>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
(function() {
var status = $('.status'),
poll = function() {
$.ajax({
url: 'status.json',
dataType: 'json',
type: 'get',
success: function(data) { // check if available
status.text('Offline!');
if ( data.live ) { // get and check data value
status.text(data.info); // get and print data string
clearInterval(pollInterval); // optional: stop poll function
}
},
error: function() { // error logging
console.log('Error!');
}
});
},
pollInterval = setInterval(function() { // run function every 2000 ms
poll();
}, 2000);
poll(); // also run function on init
})();
</script>
</body>
</html>
{
"live": false,
"info": "Online!"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment