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!
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.