Devan Browning
Devan Browning

Reputation: 31

AJAX in WordPress only returns 0

I'm trying to utilize WordPress's admin-ajax feature in order to build a dynamic admin panel option-set for a plugin. Essentially, once an option is selected from a dropdown (select/option menu), PHP functions will sort through and display more dropdown menus that fall under the dropdown above it. I began with a simple return that I was hoping to utilize later down the line, but I can't seem to get the text to print out without running into unidentified issues.

The AJAX I set up puts out a 200 status but the response never builds, and I'm left with 0 as my result. Here's the code:

JS/jQuery built into PHP function ajax-action()

$ = jQuery;
$('#platform').change(function(e) {
  var data = {
    action: 'action_cb',
    type: 'POST',
    dataType: 'json',
    error: function(XMLHttpRequest, textStatus, errorThrown) {
      console.log(errorThrown);
    },
    success: function(response) {
      $('#user_id').val(response);
    }
  };
  $.ajax(ajaxurl, data, function(data) {
    $('#user_id').val(data);
  });
  e.preventDefault();
});

PHP functions and add-actions

add_action('wp_ajax_action_cb','action_cb');
add_action('admin_footer','ajax_action');
function action_cb() { $platform = 'test'; echo json_encode($platform); wp_die(); };

My question is: how can I fix this and prevent it from continuing to happen? I'd like to return the actual results and not 0.

Upvotes: 3

Views: 3248

Answers (7)

en0ndev
en0ndev

Reputation: 692

For those by the "Load More" problem.

Normally "0" is used instead of false.

I found such a solution.

So that 0 does not come. Try this code with false.

PHP

ob_start(); // start the buffer to capture the output of the template
get_template_part('contents/content_general');
$getPosts[] = ob_get_contents(); // pass the output to variable
ob_end_clean(); // clear the buffer
if( $read == $articles->found_posts )
$getPosts[] = false;

JS

if( posts[i] == false )
$(".load_more_button").fadeOut();

Upvotes: 0

lassemt
lassemt

Reputation: 156

Ok, I have been recreating your code now in my own project and noticed that the javascript you shared returned the ajax-object and not the results. So what I come up with is a bit rewriting, but is worked fine when I tried it.

$j = jQuery.noConflict();

$j('#platform').change(function(e) {

    $j.ajax({
        url: ajaxurl,
        type: 'POST',
        dataType: 'json',
        data: {
            action: 'action_cb',
        }           
    }).done(function( data ) {
        // When ajax-request is done.
        if(data) {
            $j('#user_id').val(data);
        } else {
            // If 0 
        }
    }).fail(function(XMLHttpRequest, textStatus, errorThrown) {
        // If ajax failed
        console.log(errorThrown);
    });

    e.preventDefault();

});

I hope the comments explain good enough how it is working. Note how I'm using $j instead of just $ for the jQuery.noConflict mode.

Upvotes: 0

Kapil Yadav
Kapil Yadav

Reputation: 706

Hope this helps. I have already explained standard way of using ajax in wp.

Wordpress: Passing data to a page using Ajax

Upvotes: 0

Beneris
Beneris

Reputation: 637

To prevent WP adding zero into response i always using die(); insted of wp_die();

and registering function:

add_action( 'wp_ajax_action_cb', 'action_cb_init' );
add_action( 'wp_ajax_nopriv_action_cb', 'action_cb_init' );

function action_cb_init() {

}

When calling to function with AJAX use action: 'action_cb'

Upvotes: 0

milan kyada
milan kyada

Reputation: 579

just make small change in your AJAX. I am assuming you're logged in as admin. replace action in data object with data:"action=action_cb",

 var data = {

            data:"action=action_cb",
            type: 'POST',
            dataType: 'json',
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                console.log(errorThrown);
            },
            success: function(response) {
                $('#user_id').val(response);
            }
        };
        $.ajax(ajaxurl,data,function(data){
            $('#user_id').val(data);
        });

Upvotes: 0

Josh
Josh

Reputation: 111

As per the wordpress documentation:

https://codex.wordpress.org/AJAX_in_Plugins (Reference "Error Return Values")

A 0 is returned when the Wordpress action does not match a WordPress hook defined with add_action('wp_ajax_(action)',....)

Things to check:

  1. Where are you defining your add_action('wp_ajax_action_cb','action_cb');? Specifically, what portion of your plugin code?

  2. Are you logged into wordpress? You mentioned the admin area, so I'm assuming so, but if you are not, you must use add_action('wp_ajax_nopriv_{action}', ....)

Additionally, you didn't share the function this is tied to: add_action('admin_footer','ajax_action');

And lastly, why are you using "json" as the data type? If you are trying to echo straight HTML, change data type to 'html'. Then you can echo directly on to page (or as a value as you are doing). Currently, you are trying to echo a JSON object as a value in the form...

So your code would look like so:

function action_cb() { $platform = 'test'; echo $platform; p_die(); };

...and your AJAX could be:

<script type = "text/javascript">
jQuery.ajax({
url: ajaxurl,
type: 'post',
data: {'action' : 'action_cb'},
success: function (data) {
    if (data != '0' && data != '-1') {
        {YOUR SUCCESS CODE}
    } else {
        {ANY ERROR HANDLING}
    }
},
dataType: 'html'
});
</script>

Try This:

<script>
$ = jQuery;
$('#platform').change(function(e) {
var data = {
data: {'action' : 'action_cb'},
type: 'POST',
dataType: 'json',
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log(errorThrown);
},
success: function(response) {
$('#user_id').val(response);
}
};
$.ajax(ajaxurl, data, function(data) {
$('#user_id').val(data);
});
e.preventDefault();
});    
</script>

Upvotes: 1

Siarhei Razuvalau
Siarhei Razuvalau

Reputation: 99

Probably you need to add

add_action('wp_ajax_nopriv_action_cb', 'action_cb');

https://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_(action)

Upvotes: 0

Related Questions