So i’m using this configuration for an AJAX call in the administrative area (like this):
add_action( 'admin_head', 'ajaxPerNgg' );
function ajaxPerNgg(){ ?>
<script type="text/javascript" >
jQuery(document).ready(function() {
jQuery("#message").remove();
jQuery("#errore a#attivo").click(
function(){
var data = {
action: 'my_action'
};
jQuery.post(ajaxurl, data, function(response) {
if(response == "attivato")
jQuery("#errore a#inattivo").attr("id","completato").html("Attivato");
else
jQuery("#errore a#inattivo").attr("id","attivo").html("Attivalo ora");
});
}
);
});
</script>
<?php }
add_action('wp_ajax_my_action', 'my_action_callback');
function my_action_callback() {
echo 'attivato';
die();
}
It’s just a test code, but it always return 0 instead of the string “attivato”. It also find the ajax url correctly, without a 404 error.
What is the problem?
Add this as well:
add_action('wp_ajax_nopriv_my_action', 'my_action_callback');
. Notice thenopriv
.It will solve your problem!
I had the same problem. Solution:
If you dont add both (with and without nopriv) it will work in either signed in mode or signed out mode only. nopriv is for signed out, the other is for signed in.
Not sure if this is your problem, but I was getting a response of just “0” and it took me the longest time to figure it out. Aside from making sure you put
exit
ordie
at the end of your php function, I found out that you have to put youradd_action('wp_ajax_...
bit at the top level of your plugin. I had it nested inside myadmin_menu
hook, which didn’t work. I’m not sure if your code above is part of an include inside a function from your top level plugin php file (like mine was).