I am creating a simple wordpress plugin and trying to use AJAX, but I always get 0 in ajax response.
<script type="text/javascript" >
jQuery(document).ready(function($) {
var data = {
action: 'my_action',
whatever: '1234'
};
jQuery.post("http://localhost/taichi/wp-admin/admin-ajax.php", data, function(response) {
alert(response);
});
});
</script>
<?php
add_action('wp_ajax_my_action', 'my_action_callback');
add_action( 'wp_ajax_nopriv_my_action', 'my_action_callback' );
function my_action_callback() {
echo "test";
die();
}
what am I doing wrong?
You have to put the add_action at the complete bottom of your file or else it won’t find the callback function
Try to change :
To :
And check if it is working on the admin side first. It should work fine.
Error Return Values
If the AJAX request fails when the request url is wp-admin/admin-ajax.php, it will return either
-1 or 0
depending on the reason it failed.Read this
Edit
admin-ajax always return default ‘0’ as output.so while you alerting response you will
0 only
.usingdie()
in callback function will terminate that.Had the same problem, it turned out that my callback was inside a php file which was only included to my “Theme Options” page.
To check if the function is able to trigger trougth admin-ajax.php try to add
var_dump(function_exists("your_callback_name"));
to the bottom of the wp-admin/admin-ajax.php (beforedie( '0' );
) and then have a look to your ajax output.Try the following code in your plugin file. or in function.php