How can I run AJAX on a button click event?

The question:

Update: I managed to get the AJAX working, but not in the click event. I updated the question to match this.

I’m trying some code I found on the page: ‘AJAX in Plugins’.

However I can’t get it to work, and I Don’t really know where to start looking.
It works when I remove the click function and just run the code on pageload.

I have a Javascript file that looks ike this:

jQuery(document).ready(function(){
    jQuery("#createremotesafe").click(function(){
        alert ('test');
        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('Got this from the server: ' + response);
        });
    });    
});

and somewhere in my PHP script that generates the button that should execute the Javascript (i.e. the admin page), and also the rest of the page:

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

I get both the Alert ('test') and the echo 'test2', but not the response alert. There are no Javascript errors or anything. My code is definitely running, since I can see both ‘test’s, but why isn’t AJAX getting any response?
Does my php function disappear after page load? Maybe I can’t/shouldn’t use the built in wp AJAX functions?

It also doesn’t show an empty alert box, just nothing happens.

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

Start from a working code base..

add_action('in_admin_header', 'my_ajax_button');

function my_ajax_button() {
    echo '<a href="#ajaxthing" rel="nofollow noreferrer noopener" 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).


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment