Admin Ajax is returning 0

The question:

I am relatively new to jQuery and AJAX in particular. I have a small issue with the return value always being 0, though I think this is actually the success message and it’s not returning anything.

I have scoured the Google-verse and I have the die() function on the PHP callback and I believe the add_actions are correct.

I am working on a local host, though I doubt that affects it and this is all in the admin, not front end. I also checked that the js is enqueued and localised.

I get a 200 OK message in the chrome developer area.

I also tested out the basic AJAX from http://codex.wordpress.org/AJAX_in_Plugins and it also returned 0, which makes me wonder if it is something other than the code outlined below.

Right now I am just trying to make it send something back to the jQuery. Any help would be appreciated.

The jQuery

jQuery(document).ready(function(){
    jQuery('.cl_link_buttons').val('id').click(function() {

            var currentid = jQuery(this).attr('id');

            //alert(currentid);
            console.log(currentid);

            jQuery.ajax ( data = {
                action: 'cleanlinks_ajax_get_post_data',
                url: ajaxurl,
                type: 'POST',
                dataType: 'text',
                "currentid" : currentid

            });

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

                var dataz = response;
                alert( dataz );
                console.log (dataz); //show json in console


            });

            return false;

    }); //end click event
}); //end doc ready

The PHP

add_action("wp_ajax_cleanlinks_ajax_get_post_data", "cleanlinks_ajax_get_post_data");
add_action("wp_ajax_nopriv_cleanlinks_ajax_get_post_data", "cleanlinks_ajax_get_post_data");

function cleanlinks_ajax_get_post_data() {

$from_ajax =  $_POST['currentid'];

echo "do" . $from_ajax . "something";

die();


}

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

A 0 response means either that the action is not set (in the ajax data) or that the action’s callback function cannot be found.

Method 2

What you have to do is add die();at the end of your function.

See the reason and more here: http://codex.wordpress.org/AJAX_in_Plugins

Notes:

  • You should echo something before executing die. This will prevent server errors, and will help when debugging.

Method 3

I had this problem too, and it was the fact that I was using return instead of echo in my PHP function. Changing it to echo fixed it.

function doAjax() {
    $result = getPosts();
    echo json_encode($result, true);
    die();
}

Method 4

So I worked it out. It was not the jQuery as such though I have improved that, it was the placement of the call back function. I moved it over to the main plugin file and it worked.

Method 5

I got same problem. And solved it. You must send “action” variable like in example:

var dataString = {lat: '55.56', lng: '25.35', action:'report_callback'};
 $.ajax({                            
        url: "http://domain.net/wp-admin/admin-ajax.php",  
        type: "POST",
        //some times you cant try this method for sending action variable
        //action : 'report_callback',
        data:dataString,        
        success: function(data){ 
            console.log(data);

            },
        error: function() {
            console.log("Error");            
        }
    });

Because in wp-admin/admin-ajax.php is handler for action variable:

if ( empty( $_REQUEST['action'] ) ) {...}
Line 26

Method 6

Try running this code on the console

jQuery.post(ajaxurl, {action:'cleanlinks_ajax_get_post_data'}, function(response) {
     console.log (response);
});

I can see many things wrong about your JavaScript code and that might be the reason.

Method 7

jQuery(document).ready(function(){
    jQuery('.cl_link_buttons').val('id').click(function() {
       $.ajax({
            type:'POST',
            url: ajaxurl,
            data: {
                action : 'ajax_filter',
                currentid : 'currentid'
            },
            success: function (result) {
                console.log(result);
                $result = $(result);
                        $result.fadeIn('7000');
                        $("#showresults").html(result);

            },
            error: function (xhr, status) {
                alert("Sorry, there was a problem!");
            },
            complete: function (xhr, status) {
                $('#showresults').slideDown('slow')
            }
            });
     });
}); 

//code function php

<?php
    add_action( 'wp_ajax_nopriv_ajax_filter', 'ajax_filter' );
    add_action( 'wp_ajax_ajax_filter', 'ajax_filter' );
    function ajax_filter(){
        $date = isset($_POST['date']) ? $_POST['date'] : 0;
        echo $date;
        die();
    }
?>

Method 8

Just for reference, anybody coming from shortcode development, if you are getting a proper response through WordPress Ajax request but a 0 is getting appended, it’s only because you are ‘echo’ing instead of ‘return’ing. Shortcodes are never meant to ‘echo’ or output anything. Just another scenario.

Method 9

I had the same problem, to fix it I used wp_die() at the end of my function just after an echo. Don’t forget to pass your action on your script.

To be sure, check if your function has to use wp_ajax_nopriv like wp_ajax.

Method 10

Just for reference, for anyone who get here googling “ajax request is returning 0”:
Remember when you add ajax action to object’s method to be sure methods access modifier is public.

add_action( 'wp_ajax_my_action', [$object, 'my_method']);

add_action just silences if it can’t call your method outside of $object.

Method 11

If you don’t use wp_localize_script() function to set ajax url, admin ajax returns 0. I think it’s WordPress bug. Here’s is an example :

    wp_enqueue_script( 'search_js', get_template_directory_uri() . '/js/search.js', array( 'jquery' ), null, true );    
    wp_localize_script( 'search_js', 'ajaxurl', admin_url( 'admin-ajax.php' ) );

The javascript file (search.js) :

    $('#search_input').autocomplete({
    source: function(request, response) {

        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: ajaxurl,
            data: 'action=my_custom_action_search&search_criteria=' + request.term,
            success: function(data) {
                response(data);
            },
            error: function(errorThrown){
                console.log(errorThrown);
            } 
        });
    },
    minLength: 3
});

Method 12

Those who get error 0 :), action => ‘action’

var data = { 'action': 'firmabilgilerikaydet', 'data': form_data };

$.post(ajaxurl, data, function(response) { alert(response); });

Method 13

If you are using localhost and your php server side code is in a plugin file first login to admin dashboard and refresh the plugin page. Secondly, check if the plugin is activated. Then go to frontend and refresh and try sending again.

Method 14

YOU TRY:

add_action('init', 'ly_form_ajax_init');


function ly_form_ajax_init() {
    wp_register_script('ly-form-ajax-script', plugins_url().'/ly-form/js/ly-script.js' , array('jquery'));
    wp_enqueue_script('ly-form-ajax-script');

    wp_localize_script('ly-form-ajax-script', 'ly_form_ajax_object', array(
        'ajaxurl' => admin_url('admin-ajax.php'),
        'redirecturl' => home_url(),
        'loadingmessage' => __('')
    ));
}
// Action is: contact_ajax
add_action( 'wp_ajax_contact_ajax', 'my_function' );
add_action( 'wp_ajax_nopriv_contact_ajax', 'my_function' );

function my_function(){
    ob_clean();
    echo "http://sanvatvungcao.com";
    wp_die();
}

/**
 * Short code in page like this: [ly-form]
 * @param type $atts
 * @param type $content
 * @return string
 */
function ly_form_shortcode($atts, $content = "") {
    echo html_form_code();
}
add_shortcode('ly-form', 'ly_form_shortcode');

//HTML Form will show,
function html_form_code() {
    $html = "";
    $html.= '';
    $html.= '';

    $html.= '        

Họ đệm *

'; $html.= '

Tên *

'; $html.= '

Địa chỉ *

'; $html.= '

Email *

'; $html.= '

Nội dung * dg

'; $html.= ' '; $html.= ''; $html.= ''; $html.= ''; return $html; } AND HERE js (ly-script.js): ( function( $ ) { $(document).ready(function () { // Perform AJAX form submit $('form.ly-form-ex').on('submit', function(e){ e.preventDefault(); $('#loading').html('loading...'); var dataString = {action:'contact_ajax'}; $.ajax({ type: "POST", url: ly_form_ajax_object.ajaxurl, data: dataString, success: function (data) { $('#loading').html(data); }, error: function (errorThrown) { alert(errorThrown); } }); }); }); // end ready } )( jQuery );

Hope it is helpful for you,
Best

Method 15

Try adding an if statement:

function my_function(){
$id = $_POST['variation_id'];

    if(isset($_POST['variation_id'])) { 


//your coded function


die();
}



}// end function


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment