Reputation: 79
I'm trying to make an app that grabs a song a user is listening to using a scraper. Right now I can get the user to visit the page and see the song title that is being listened to, but if the song updates they will need to refresh the entire page on their own. I am looking for a way to run the code I have in the routes file and then render the page with the song data, then check every now and then if the data has changed and then refresh the section of the page with the new data.
Here's what I want to happen:
Thanks.
Upvotes: 0
Views: 2568
Reputation: 6179
You'll want to use ajax.
You can create a new route on your nodejs server that returns song data as json rather than rendering an EJS file to the client.
Imagine your code is currently like this:
app.get('/songinfo', function(req, res) {
request.get('http://songinfo.com/songs', function(err, res, data) {
res.render('songinfo.ejs', data);
});
});
You can change it to the following:
function getSongInfo(callback) {
request.get('http://songinfo.com/songs', function(err, res, data) {
callback(data);
});
}
app.get('/songinfo', function(req, res) {
getSongInfo(function(data) {
res.render('songinfo.ejs', data);
});
});
app.get('/raw-songinfo', function(req, res) {
getSongInfo(function(data) {
res.setHeader('content-type', 'application/json');
res.send(data);
});
});
What I've done here is pull out the getSongInfo
logic to keep our app DRY, and added a second route that also uses that function, and rather than sending back the data in an ejs file, sends it back in json. Now, in your ejs file, you can add the logic for calling this route:
<button onclick='reloadData()'> Reload me! </button>
<script type='text/javascript'>
function reloadData() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
if(xmlhttp.status == 200){
// Update the data in your app somehow...
// example:
var responseData = JSON.parse(xmlhttp.responseText);
document.getElementById('songs-count').innerHTML = responseData.length;
} else {
alert('something went wrong!');
}
}
}
}
</script>
Upvotes: 1