开发者

Ajax in Wordpress plugin

开发者 https://www.devze.com 2023-03-19 19:26 出处:网络
I am creating a simple wordpress plugin and trying to use AJA开发者_开发百科X, but I always get 0 in ajax response.

I am creating a simple wordpress plugin and trying to use AJA开发者_开发百科X, 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 :

jQuery.post("http://localhost/taichi/wp-admin/admin-ajax.php", data,   function(response)

To :

jQuery.post(ajaxurl, data, function(response) 

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.using die() 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 (before die( '0' );) and then have a look to your ajax output.


Try the following code in your plugin file. or in function.php


    
    jQuery(document).ready(function($){
    var ajaxURL = 'http://localhost/taichi/wp-admin/admin-ajax.php';
    var dataString = 'action=mnd_news';
    $.ajax({
    type: "POST",
    url: ajaxURL,
    data: dataString,
    cache: false,
    success: function(response){
    if(response != 'error') {
    alert(response);
    }
    }
    });
    });
    
    add_action('wp_ajax_mnd_news', 'get_mnd_ajax');
    add_action( 'wp_ajax_nopriv_mnd_news', 'get_mnd_ajax' ); 
    function get_mnd_ajax() {
    echo "test";
    die();
    }

0

精彩评论

暂无评论...
验证码 换一张
取 消