1

Im using the following function to call an ajax request, and fill certain corresponding divs with the response:

$( function() {

    $(document).ready(function() {

        var postData = "";

        $.ajax( {
            url : \'functions/ajax_api.php?\',
            type : \'post\',
            data : postData,                
            success : function( resp ) {
                $(\'#id1\').html($(\'#id1\' , resp).html());
                $(\'#id2\').html($(\'#id2\' , resp).html());
            }
        });
           return false;
    });

});

The function works fine. My question is how can I call it automatically every few seconds?

I tried using window.setTimeout(function, 3000) but I couldnt set it up correctly.

helloworld
  • 527
  • 6
  • 21
  • 1
    setInterval is what you need – aorfevre Jun 18 '15 at 23:42
  • It might help to show the *exact* code you tried and what *specifically* went wrong. – showdev Jun 18 '15 at 23:46
  • possible duplicate of [Calling a function every 60 seconds](http://stackoverflow.com/questions/3138756/calling-a-function-every-60-seconds) – showdev Jun 18 '15 at 23:58
  • 1
    `$( function() {//code});` and `$(document).ready(function() {});` are the same.. the anonymous function inside is called whenever the jQuery is loaded in your page. And then use `setTimeout(f, timeinms)` as others suggested. – xdevel Jun 19 '15 at 00:00

3 Answers3

5

use setInterval(); instead of .setTimeout()

Let me help you a little bit with that

var interval , setItinterval; // just a variables you can change names
interval = function(){
    // ajax code here
}

to run it .. use:

setItinterval = setInterval(interval , 3000);

to stop it .. use

clearInterval(setItinterval);

Make sure to read setInterval for more information.

For Complete answer and Last thing I want to say when using setInterval(); Its better to use visibilitychange to avoid server error , server load or something like that

document.addEventListener('visibilitychange',function(){
    if(document.visibilityState == 'visible'){
        // user view the page
    }else{
        // user not see the page
    }
});
Mohamed-Yousef
  • 23,946
  • 3
  • 19
  • 28
2

You can use setTimeout() or setInterval, but setInterval may result in multiple simultaneous ajax calls if those calls take too long to respond. That isn't a problem if you call setTimeout() in the ajax success callback.

To use setTimeout(), first wrap your ajax call in a function. You can then add a call to setTimeout() to the ajax success callback. You also need to call the function once to start of the looping.

$(function() {
    function postData() {
        var postData = "";
        $.ajax({
            url: 'functions/ajax_api.php?',
            type: 'post',
            data: postData,                
            success: function(resp) {
                $('#id1').html($('#id1', resp).html());
                $('#id2').html($('#id2', resp).html());

                // Call postData again after 5 seconds.
                setTimeout(function() { postData(); }, 5000);
            }
        });
    }

    // Call postDate the first time to start it off.
    postData();
});

Note: With the call to setTimeout in the success callback, the cycle will break if an ajax call fails. You may want that, but if you want it to act more like setInterval, you can place the call to setTimeout in the complete callback.

John S
  • 21,212
  • 8
  • 46
  • 56
  • I think you mean `setTimeout` in the callback. Otherwise you'd be creating multiple intervals indefinitely – Jan Jun 19 '15 at 00:04
  • By the way, I vastly prefer doing it this way. If there's any risk of the initialiser ever being run through an event that could be called multiple times you WILL end up with multiple intervals. What you also need to do is store and clear the timeout in an outer scope though, otherwise it's the same issue as with interval. – Jan Jun 19 '15 at 00:10
  • @Jan - Now I think you wrote "interval" when you meant "timeout". – John S Jun 19 '15 at 00:21
  • Hah! Nah I meant interval. Not as in the function name, rather that a self-referencing `setTimeout` is an interval (something that repeats every n time-unit). So if you don't clear it, you will end up with the same issues as with `setInterval` if it's possible to instantiate it multiple times. This might not be the case right here, but that's why I prefer using it. – Jan Jun 19 '15 at 00:25
  • @Jan - Sorry, I somehow missed the word "as" and read it as "otherwise it's the same issue with interval". – John S Jun 19 '15 at 00:44
0

Here's some example code that will do it (note that it runs the function when the document loads, and then starts the interval). You can always use clearInterval(refresh_interval) if you need to stop it.

var refresh_interval;

function update_content() {
    $.ajax({
        url : \'functions/ajax_api.php?\',
        type : \'post\',
        data : postData,                
        success : function( resp ) {
            $(\'#id1\').html($(\'#id1\' , resp).html());
            $(\'#id2\').html($(\'#id2\' , resp).html());
        }
    });
}

$(document).ready(function() {
    update_content();
    setInterval(update_content, 3000);
}

The relevant documentation for using intervals is here: https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setInterval

Though you may want to look into Server Sent Events, it's probably a better solution for what you want.

The Busy Wizard
  • 956
  • 1
  • 7
  • 11