ajax for visitors wordpress

You also need to add your action callback to non-privileged users. It works the same way as you registered your my_action_callback – you just need to add another line.

add_action( 'wp_ajax_my_action', 'my_action_callback' );
add_action( 'wp_ajax_nopriv_my_action', 'my_action_callback' );

Notice the wp_ajax_nopriv_ in front of your action – this tells WordPress that any user may call this action., whereas wp_ajax_ only allows logged in users to run the script.

After properly formatting and cleaning your code, I saw a few things.

  • You added the my_action_callback twice to the wp_ajax_my_action
  • You used admin_footer instead of wp_footer => there was no output on the frontend
  • Your ajaxurl was not defined

Cleaning all this up, you get your Version working nicely:

function my_action_javascript() {
    ?>
    <script type="text/javascript" >
        var ajaxurl="<?php echo admin_url("admin-ajax.php'); ?>';
        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
            $.post(ajaxurl, data, function(response) {
                alert('Got this from the server: ' + response);
            });
        });
    </script>
    <?php
}

function my_action_callback() {
    global $wpdb; // this is how you get access to the database
    $whatever = intval( $_POST['whatever'] );
    $whatever += 10;
    echo $whatever;
    die(); // this is required to return a proper result
}


add_action( 'wp_ajax_my_action', 'my_action_callback' );
add_action( 'wp_ajax_nopriv_my_action', 'my_action_callback' );