Ajax in WordPress plugin

I am creating a simple wordpress plugin and trying to use AJAX, 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?

Related posts

Leave a Reply

5 comments

  1. 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.

  2. 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.

  3. 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.

  4. 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();
        }