2

I want to update information in a WordPress widget every 30 seconds. Therefore I thought I'd better use some Ajax.

I found this here on the WordPress Codex and added it to my functions.php:

add_action( 'admin_footer', 'my_action_javascript' ); // Write our JS below here

function my_action_javascript() { ?>
<script type="text/javascript" >
jQuery(document).ready(function($) {

    var data = {
               'action': 'my_action',
               'whatever': 1234
    };

    // since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
    jQuery.post(ajaxurl, data, function(response) {
        alert(response);
    });
});
</script> <?php
}

add_action( 'wp_ajax_my_action', 'my_action_callback' );

    function my_action_callback() {
    global $wpdb; // this is how you get access to the database
    $bla = get_option("airtime_now_playing");
    echo $bla;
    wp_die(); // this is required to terminate immediately and return a proper response
}

It works fine and does retrieve what I need.

How can I fire this not only once but every 30 seconds?

Thanks a lot!

Mister Woyng
  • 391
  • 2
  • 16
  • 1
    Have a look at this http://stackoverflow.com/questions/2170923/whats-the-easiest-way-to-call-a-function-every-5-seconds-in-jquery – Enrico Jan 06 '16 at 17:23
  • Thank you. Yes...this was the same problem as I had, and it was solved there. – Mister Woyng Jan 07 '16 at 10:20

1 Answers1

6

You need to use setInterval function. FYI: If you need to raise the ajax call only once after 30 seconds you need to use setTimeout that wait 30 seconds and then do function once.

setInterval(function(){
    jQuery.post(ajaxurl, data, function(response) {
        alert(response);
    });
}, 30000);
erikscandola
  • 2,854
  • 2
  • 17
  • 24