-4

Using javascript / another client side scripting language I need to show the result of a http get request, and update every X seconds without refreshing. The api I am working with is external and works like this: You send it a request, no parameters, and it returns a number. I need to display this in a static html site and live update it every 2 seconds.

So far I have been able to live update using functions like Math.random() and setInterval but my trouble is making a GET request inside the JavaScript, to an external domain. I have a working php script that provides the result but I do not know how to integrate this into the JS

Jay Williams
  • 13
  • 1
  • 4
  • 1
    Welcome to SO. Please visit the [help] and take the [tour] to see how and what to ask. HINT: Post effort and code. – mplungjan Jul 09 '16 at 16:16

2 Answers2

1

I strongly advice to call the function again inside the success of the api call. A solution using setInterval may hammer the site even when it gives errors. Also the request can take longer than 2 second to execute

Here I use jQuery for simplicity's sake

Use setTimeout inside the success:

function getIt() { 
  $.get("url",function(data) { 
    $("#container").text(data); 
    setTimeout(getIt,2000);
  });
}
getIt();

If the URL is crossdomain, you may want to look into JSON and CORS: How to get a cross-origin resource sharing (CORS) post request working

Community
  • 1
  • 1
mplungjan
  • 169,008
  • 28
  • 173
  • 236
-1

Just use Ajax and setInterval():

setInterval(function(){ 

//your Ajax call goes here 

}, 2000);
otherstark
  • 142
  • 6
  • Never use interval on Ajax. – mplungjan Jul 09 '16 at 16:22
  • @mplungjan what is the reason for not doing as this answer suggests? Why not use Ajax inside interval? – Rasclatt Jul 09 '16 at 16:22
  • Because you may hammer the site even when it gives errors. Also the request can take longer than 2 second to execute – mplungjan Jul 09 '16 at 16:23
  • 1
    main downfall is the time it takes the get back the response is not determined, so multiple calls could happen before the response ever comes back – otherstark Jul 09 '16 at 16:24
  • @mplungjan I really only bring up the question of why because it's one thing to say don't do something, but if you have no reason, It's opinion at that point and doesn't give viewers any reason to trust your suggestion. – Rasclatt Jul 09 '16 at 16:37
  • @Rasclatt I'll copy the reason to my answer. I did expect to have the discussion in the comment but did not feel I had the time when I posted it – mplungjan Jul 10 '16 at 15:57
  • 1
    @mplungjan Great! Now visitors will know why your answer is a better one! – Rasclatt Jul 10 '16 at 16:03