Hook AJAX in WordPress

First of all you need to add hooks in proper way

// For the users that are not logged in
add_action( 'wp_ajax_nopriv_addItemAJAX', 'addItemAJAX_callback' );  

// For the users that are  logged in:  
add_action( 'wp_ajax_addItemAJAX', 'addItemAJAX_callback' );

// ajax handler
function addItemAJAX_callback()
{
    // code goes here
    // since $debugArray is an array, so 
    die(json_encode($debugArray)); // last line
}

One hook will work when user is logged in and another will work when user is not logged in (for any user). If you are making ajax request for logged in users then, wp_ajax_nopriv_ hook is required.

Keep your js/ajax code in a separate file in yourthemefolder/js/myAjaxScript.js and also keep following code in your functions.php file

add_action('wp_enqueue_scripts', 'my_load_scripts');
function my_load_scripts()
{
    // for pluggin, you may use "plugin_dir_url( __FILE__ )"
    wp_enqueue_script( 'my_ajax-script', get_stylesheet_directory_uri() . '/js/myAjaxScript.js', array('jquery') );

    // Following code will let you use "ajaxObj.ajax_url" to get the
    //  ajax url (admin-ajax.php) in your my_ajax_scriptjs file
    wp_localize_script(
        'my_ajax-script', 'ajaxObj', array( 'ajax_url' => admin_url( 'admin-ajax.php' )                
    ));
}

In your my_ajax_script.js file, you may code like this

var data = {
     action: 'addItemAJAX_callback',
     // ...
};
$.getJson(ajaxObj.ajax_url, data, function(response) {
     // response is an object
     // ...
});

Alos remember, when using ajax from admin panel, you don’t need to use wp_localize_script, since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php.

Leave a Comment