Wordpress ajax example

Categories: 

Tags: 

  • Simple ajax example to show some info every 3 seconds, loading it from php in your plugin or theme functions.php file

Javascript

  • Include this code in your theme header.php for example
<script type="text/javascript">
    jQuery(document).ready(function() {
        function refreshData()
        {
            jQuery.ajax({
                url: <?php echo admin_url('admin-ajax.php'); ?>, 
                data: 'action=function_example',
                success: function(data) {
                    jQuery('#ajax-results').html(data);
                }
            });
        }
 
        refreshData();
        var auto_refresh = setInterval(function(){ refreshData() }, "3000");
    });
</script>
 
<!-- div to refresh -->
<div id="ajax-results"></div>

PHP

  • Include this in your plugin or theme functions.php
function function_example()
{
    // echo whatever you need to show it every 3 seconds...
    echo "Whatever you want";
}
 
add_action( 'wp_ajax_function_example', 'function_example' );