Reputation: 35
I'm wrote WordPress ajax plugin but admin-ajax.php always return 0 and don't work.
Here is my code:
add_action( 'wp_ajax_example_ajax_request', 'example_ajax_request' );
add_action( 'wp_ajax_nopriv_example_ajax_request','example_ajax_request' );
wp_enqueue_script( 'test', plugins_url( 'actions/js/test.js', __FILE__ ), array('jquery'), '1.0', true );
wp_localize_script( 'test', 'ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
function example_ajax_request() {
echo"d";
die();
}
My javascrip test.js file:
jQuery(document).ready(function($) {
var fruit = 'Banana';
$.ajax({
url: ajaxurl,
data: {
'action':'example_ajax_request',
'fruit' : fruit
},
success:function(data) {
console.log(data);
},
error: function(errorThrown){
console.log(errorThrown);
}
});
});
How this work?
Thanks.
Upvotes: 1
Views: 1229
Reputation: 254182
There is an error in your query script:
jQuery(document).ready(function($) {
var fruit = 'Banana';
$.ajax({
url: ajax_object.ajax_url, // =================> HERE is the problem
data: {
'action':'example_ajax_request',
'fruit' : fruit
},
success:function(data) {
console.log(data);
},
error: function(errorThrown){
console.log(errorThrown);
}
});
});
You need to use ajax_object
with ajax_url
defined in wp_localize_script()
this way:
url: ajax_object.ajax_url,
Reference:
Upvotes: 1