1

How can I use AJAX to check a file, like, every 30 seconds, and then just print the result? I would prefer to use jQuery, but just plain javascript is okay too.

P.S. I've been searching for how to do this for a while.

neex1233
  • 373
  • 2
  • 3
  • 16
  • 2
    jQuery's Ajax and `setTimeout()` will do the trick. https://developer.mozilla.org/en/DOM/window.setTimeout – Pekka Dec 15 '11 at 21:37
  • When I search Google for [ajax every 30 second](https://www.google.com/search?q=ajax+every+30+second), I get several related questions, such as http://stackoverflow.com/q/4450579/27727 and http://stackoverflow.com/q/2881934/27727 in addition to non-SO info. Further, looking under "Related" on the right gives several more. I'm at a loss as to what you're asking, that isn't already answered in one of those. – derobert Dec 15 '11 at 21:41

2 Answers2

2

Use setInterval to run a function every X milliseconds.

setInterval(function(){
   $.get('file', function(data){  // Use AJAX to get the file you want
      console.log(data);  // Do something with the file
   });
}, 30000); // 30000ms = 30s
gen_Eric
  • 223,194
  • 41
  • 299
  • 337
2

Something like this should help:

function getData() {
    $.get("filepath", function (data) {
        // process data...
        console.log(data);

        // Invoke the data lookup again after 30s
        window.setTimeout(function () { 
            getData();
        }, 30000); // 30s
    });
}

And then invoke the starting of the loop:

$(document).ready(function () {
    getData();
});
jabclab
  • 14,786
  • 5
  • 54
  • 51
  • 1
    Just wondering, how often should I check? (It's for a notification system) – neex1233 Dec 16 '11 at 00:16
  • 1
    It really depends on the nature of your notifications. If it's something like checking for emails then a minute would be fine but if it's something that you want to happen as soon as possible I'd go for about 5 seconds. Have a play around with it- you want to strike a balance between usability and not polling your server to death :-) – jabclab Dec 16 '11 at 09:03