Ajax in Wordpress Plugin

I am creating a simple wordpress plugin and trying to use AJAX, but always get 0 in the 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?

+5
source share
5 answers

You must put add_action in the full bottom of your file, otherwise it will not find the callback function

+1
source

Try changing:

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

To:

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

And check if it works first on the admin side. It should work fine.

+1
source

AJAX , URL- - wp-admin/admin-ajax.php, -1 or 0 , .

admin-ajax '0' output.so, , 0 only.using die() .

0

, , php , " ".

, trougth admin-ajax.php, var_dump(function_exists("your_callback_name")); wp-admin/admin-ajax.php( die( '0' );), ajax.

0

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

All Articles