I'm pretty new in Wordpress plugins, so I have a question for you guys. I have a problem with admin-ajax call on the viewer-facing side of site. I'm using shortcodes in wordpress posts, to make a link, which must call ajax action. Unfortunately admin-ajax.php returns 0 every single time. Take a look on my code and maybe you can help me to discover what i'm doing wrong.
PHP side:
class myClass {
public function __construct() {
if (defined('DOING_AJAX')) {
add_action( 'wp_ajax_myAction', array($this, 'myCallback') );
add_action( 'wp_ajax_nopriv_myAction', array($this, 'myCallback') );
}
}
public function myCallback() {
echo "test";
die();
}
}
and there is Ajax call in Javascript:
jQuery(document).ready(function($) {
var link = $('a.myLink');
link.on('click', function(e) {
$.ajax({
url: 'http://127.0.0.1/myapp/wp-admin/admin-ajax.php',
type: 'POST',
data: 'myAction',
success:function(data) {
console.log(data);
},
error: function(error) {
console.log(error);
}
});
});
});
Do you have some ideas why that code isn't working and admin-ajax.php returns "0"?
Try to use the ajax call in this format :
jQuery(document).ready(function($) {
var link = $('a.myLink');
link.on('click', function(e) {
var details = {
'action': 'myAction'
};
$.ajax({
url: 'http://127.0.0.1/myapp/wp-admin/admin-ajax.php',
type: 'POST',
data: details, // data format
success:function(data) {
console.log(data);
},
error: function(error) {
console.log(error);
}
});
});
});
hope it helps...
Solved! Two things:
data: 'myAction'
replaced by
data: {
action: 'myAction'
}
and in main plugin file I had
if ( is_admin() ) {
// there should be new myClass() too
} else {
$class = new myClass();
}
thanks for suggestions!
Try with Enque JQuery Form Plugin Before Your Ajax request.
add_action('wp_print_scripts','include_jquery_form_plugin');
function include_jquery_form_plugin(){
wp_enqueue_script( 'jquery' );
wp_enqueue_script( 'jquery-form',array('jquery'),false,true );
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.