How can I run AJAX on a button click event?

Start from a working code base..

add_action('in_admin_header', 'my_ajax_button');

function my_ajax_button() {
    echo '<a href="#ajaxthing" class="myajax">Test</a>';
}

add_action('admin_head', 'my_action_javascript');

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

    $('.myajax').click(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
}

add_action('wp_ajax_my_action', 'my_action_callback');

function my_action_callback() {
     global $wpdb; // this is how you get access to the database

     $whatever = $_POST['whatever'];

     $whatever += 10;

             echo $whatever;

     exit(); // this is required to return a proper result & exit is faster than die();
}

That’s the code(with a minor adjustment) from the codex page, and that’s perfectly fine for me, so i’d suggest using that as a starting point.. if that’s what you initially did, at what point did it break or stop working?

NOTE: Mark is me, i use a secondary account when accessing the site from another PC(that isn’t mine).

Leave a Comment