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.
ajaxurl
defined and correct? 2) Where are you seeing theecho 'test2'
happen?