I'm currently working on an node/express app that shows several informations about the ISS. I'm using an API shared by the NASA returning JSON data.
I want the data to be updated dynamically on my page using EJS, without the need to refresh it. let's say every 1000ms.
Here's my actual code to get the ISS's current Longitude and Latitude:
Server side:
app.get("/iss", function(req, res){
var url = "http://api.open-notify.org/iss-now.json";
request(url, function(err, response, body){
if (!err && response.statusCode == 200){
var data = JSON.parse(body);
res.render("ISS", {data: data});
}
});
});
Client side :
<div class="ui main text inverted container segment">
<div class="ui huge header">Where is the ISS ?</div>
<p>Longitude : <%= data["iss_position"].longitude %> </p>
<p>Latitude : <%= data["iss_position"].latitude %> </p>
</div>
I've heard about Socket.io but i don't know if it would be optimized for my need. Also, can i get it to work by using setInterval()function ?
If yes, can you help me with that ?
Thanks for your help.
Sample api call for iss endpoint
app.get("/iss", function(req, res){
var url = "http://api.open-notify.org/iss-now.json";
request(url, function(err, response, body){
if (!err && response.statusCode == 200){
var data = JSON.parse(body);
res.send(data);
}
});
});
Client side code-
<div class="ui main text inverted container segment">
<div class="ui huge header">Where is the ISS ?</div>
<p>Longitude :<span id="longitude"> <%= data["iss_position"].longitude %> </span></p>
<p>Latitude : <%= data["iss_position"].latitude %> </p>
</div>
Assuming you are using jQuery
<script>
$.ajax({
"url":<base_url>+"/iss",
"success":function(data){
$("#longitude").html(data.iss_position.longitude);
},
"error":function(error){
//handle error here
}
})
</script>
I want the data to be updated dynamically on my page using EJS, without the need to refresh it. let's say every 1000ms.
You may need to call the Ajax function using setInterval to update send the request every 1000ms
Code for setInterval
<script>
setInterval(function(){
$.ajax({
"url":<base_url>+"/iss",
"success":function(data){
$("#longitude").html(data.iss_position.longitude);
},
"error":function(error){
//handle error here
}
})
}, 1000);
</script>
$(document).ready(function() {
setInterval(function() {
$.ajax({
"url": "http://api.open-notify.org/iss-now.json",
"success": function(data) {
$("#longitude").html(data.iss_position.longitude);
},
"error": function(error) {
console.log(error);
}
})
}, 1000);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="longitude">
</span>
You can check the snippet above and see the longitude updating.