45

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();


}
8
  • 1
    Have you verified that ajaxurl is set properly? Commented Apr 27, 2013 at 15:14
  • Does your browser console show any errors? If so, what are they?
    – s_ha_dum
    Commented Apr 27, 2013 at 15:17
  • 2
    jQuery('.cl_link_buttons').val('id').click(function() looks odd.
    – fuxia
    Commented Apr 27, 2013 at 15:26
  • Andrew, yes I believe it is correct, the request url in Chrome Inspector is showing domain/wp-admin/admin-ajax.php
    – Apina
    Commented Apr 27, 2013 at 17:08
  • @s_ha_dum No errors showing
    – Apina
    Commented Apr 27, 2013 at 17:10

15 Answers 15

52

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.

2
  • 2
    Yeah, this is the correct answer. All adding die() to the end does, is terminate the script. That answer is technically correct if you're seeing 0 appended to the END of the output, however if all you get is '0', then it means nothing was returned, and you have an error as described in this answer. Commented May 11, 2014 at 20:26
  • 1
    Or you just returned nothing on purpose in the php that handles the ajax request. Be sure to echo something out, otherwise, use .always to capture it. Commented Oct 26, 2015 at 17:12
33

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.
7
  • 10
    This is the answer to the WP AJAX 0 problem. Commented Mar 26, 2014 at 15:59
  • Actually, if you just add die() without echoing something out, this will also give you a 500 Internal Server Error, and return 0 for wp-admin/admin-ajax.php. You should always echo out something, even if you are just setting values and nothing is needed to be returned. Otherwise, if you echo nothing and die(), you have to use .always() to capture it, cause it will not be in .done(), it will be in .fail() because it dies without anything = 500 Error. Commented Oct 26, 2015 at 17:05
  • do you have some links, or working code, so we can take a look ? @SolomonClosson Commented Oct 26, 2015 at 17:18
  • All my answers have been tested in live environments. It's very simple to test this, just do a die(); in the ajax function in the functions.php file without echoing out anything prior to this, and call the action via ajax, e.g.: var testing = $.ajax( ... ); testing.fail(function(response) { console.log('Failed ' + response); }); testing.done(function(response) { console.log('Success ' + response); }); testing.always(function(response) { console.log('Ajax Request complete: ' + response); }); Commented Oct 26, 2015 at 19:33
  • You will notice, Failed will show up, the response will be a 500 Internal Server Error. Commented Oct 26, 2015 at 19:38
5

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();
}
1
  • Thank you, Man! it's working for me))
    – Pavel8289
    Commented Feb 17, 2021 at 16:27
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.

3
3

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
1
  • 4
    The OP does send an action parameter. While this may have worked for you it was not the problem here.
    – s_ha_dum
    Commented May 11, 2014 at 20:19
1

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.

7
  • Well it is coming up with a lot of things I dont fully understand. What I do understand: ReadyState 4, status 200, responseText "0". And then it comes up with the response 0. If there something in specific I should be looking for here? If there are issues with the code, please point them out and I can look into them, I am still learning jQuery.
    – Apina
    Commented Apr 27, 2013 at 17:34
  • do you have your site running live?
    – Omar Abid
    Commented Apr 27, 2013 at 17:35
  • No, it's localhost
    – Apina
    Commented Apr 27, 2013 at 17:36
  • Hard to tell. Could you try running console.info(ajaxurl); and see what it gives?
    – Omar Abid
    Commented Apr 27, 2013 at 17:37
  • 1
    try replacing ajaxurl with 'localhost/wp-admin/admin-ajax.php' and see what it gives
    – Omar Abid
    Commented Apr 27, 2013 at 18:57
1
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();
    }
?>
2
  • Just posting code is not good, can you please explain what this piece of code does?
    – bravokeyl
    Commented Mar 22, 2018 at 4:52
  • important: $date = isset($_POST['date']) ? $_POST['date'] : 0; And function die();
    – Ngocheng
    Commented Mar 22, 2018 at 6:35
1

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.

0

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.

0

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.

0

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
});
0

Those who get error 0 :), action => 'action'

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

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

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.

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

2
  • You might want to explain the why :)
    – kaiser
    Commented Mar 22, 2017 at 9:09
  • The bottom line here may be the ob_clean(); function. You can do and experience
    – Ly Van Vu
    Commented Mar 24, 2017 at 4:20
-2

Try adding an if statement:

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

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


//your coded function


die();
}



}// end function
1
  • 1
    How would that solve the problem? Note the accepted answer and the original code.
    – fuxia
    Commented Sep 23, 2013 at 2:28

Not the answer you're looking for? Browse other questions tagged or ask your own question.