0

I am trying to figure out how to make periodic AJAX calls to a cross-domain hostname. For example, how can I serve content from example.com and make an AJAX call to example.org every 30 seconds.

The canonical solution to this question is a JSONP call in a <script> tag. However, the <script> tag is just loaded once. Therefore, it can not generate periodic calls to another server - just a single call when the page loads.

Is there a way to make a periodic AJAX call to a cross-domain server?

sideshowbarker
  • 81,827
  • 26
  • 193
  • 197
Adam Matan
  • 128,757
  • 147
  • 397
  • 562
  • You'll want to look into `setInterval()` to setup your periodic calls. http://www.w3schools.com/jsref/met_win_setinterval.asp – Sean3z Feb 16 '14 at 15:37
  • How can `setInterval()` be used in the context of a `script` tag? – Adam Matan Feb 16 '14 at 15:41
  • your script tag includes the code that calls setInterval, which executes a function every interval that makes the same AJAX request – thescientist Feb 16 '14 at 15:42

1 Answers1

1

Consider the following code. We're using setInterval to call our ping() function every 3 seconds.

<script type="text/javascript">
  function ping() {
    $.ajax({
      ...
    });
  }

  setInterval(function() {
    ping();
  }, 3000);
</script>
Sean3z
  • 3,745
  • 6
  • 26
  • 33