In general, when a ajax call usgin admin-ajax.php returns zero it means that the action is not set in the request data, or that the action callback is not found.
In your case, it seems that the action callback is not found.
When performing ajax call in the frontend, you need to use the action wp_ajax_nopriv_{action}
instead of wp_ajax_{action}
:
// For admin side
add_action("wp_ajax_test_action", "_test_function");
// For frontend side
add_action("wp_ajax_nopriv_test_action", "_test_function");
function _test_function(){
die( 'success' );
}
Also, localizing script in ajax action callback has not much senses, you need to do it some where else, usually in wp_enqueue_scripts
action:
add_action( 'wp_enqueue_scripts', 'cyb_enqueue_scripts' );
function cyb_enqueue_scripts() {
// First, enqueue you ajax script
wp_enqueue_script( 'my-script', plugins_url( 'assets/js/mi-ajax-script.js', __FILE__ ) );
// Second localize the script to pass variables
wp_localize_script(
'my-script' , // handle of the script to be localized
'ajax_object' ,
array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) )
);
}
Then, in my-ajax-script.js you can access to ajax_object
created with wp_localize_script()
:
var name = "Toto";
$.ajax({
url : ajax_object.ajaxurl,
type : 'post',
data : {
'action' : 'test_action',
'data' : {
'name' : name,
}
},
success : function(response){
alert(response);
},
error : function(){
alert('error');
}
});