-1

This question already has an answer here:

I keep getting a response of 0 instead of string, which is my function echoes. Why?

code from functions.php

// enque test.js
function add_script() {
    wp_enqueue_script(
        'test',
        get_stylesheet_directory_uri() . '/js/test.js',
        array( 'jquery' )
    );
    wp_localize_script('test', 'ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' )));
}
add_action( 'wp_enqueue_scripts', 'add_script' );

// ajax function
function my_AJAX_processing_function(){
   echo 'string';
}
add_action('wp_ajax_nopriv_ACTION_NAME', 'my_AJAX_processing_function');

code from test.js

$(function () {

    var data = {
        action: 'ACTION_NAME'
    };

    jQuery.post(ajax_object.ajax_url, data, function(response) {
        alert('Got this from the server: ' + response);
    });

});

marked as duplicate by kaiser Feb 11 '14 at 0:11

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • Is test.js properly included? If it is try using jQuery(document).ready(function($) { ... }); instead of the shorthand version at the top. – Andrew Bartel Feb 10 '14 at 23:20
  • 1
    Please always search the site. – kaiser Feb 11 '14 at 0:11
  • I think nopriv does not handle logged in users and this might be the case. in PHP you should add add_action('wp_ajax_ACTION_NAME', 'my_AJAX_processing_function'); – CBeTJlu4ok Feb 11 '14 at 0:49
2

Ajax callbacks must always end with a die() to work correctly in WP.

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