AJAX in WordPress only returns 0

Solution:

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>