Hook AJAX in Wordpress

倾然丶 夕夏残阳落幕 提交于 2019-11-27 15:56:00
The Alpha

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.

brasofilo

I won't go through your code as it seems a bit hard to replicate (see SSCCE for this matter). But I'll outline how to work with Ajax and WordPress (from How to Use AJAX in a WordPress Shortcode?):

1) Enqueue and localize the JavaScript file.

Instead of enqueueing, we could print directly in the head or footer, but it's not good practice. And the localization will pass PHP values to JS in a clean fashion.
I'm assuming you're working with a theme, otherwise change get_stylesheet_directory_uri() to plugins_url().

add_action( 'wp_enqueue_scripts', 'enqueue_so_19721859' );

function enqueue_so_19721859() 
{
    # jQuery will be loaded as a dependency
    ## DO NOT use other version than the one bundled with WP
    ### Things will BREAK if you do so
    wp_enqueue_script( 
        'my-handler',
        get_stylesheet_directory_uri() . '/js/ajax.js',
        array( 'jquery' )
    );
    # Here we send PHP values to JS
    wp_localize_script( 
        'my-handler', 
        'my_handler',
        array( 
            'ajaxurl'      => admin_url( 'admin-ajax.php' ),
            'ajaxnonce'   => wp_create_nonce( 'my_ajax_validation' ) // <--- Security!
        ) 
    );
}

2) Ajax for logged and non-logged users

You gotta add a public Ajax callback too with no_priv_:

add_action('wp_ajax_addItemAJAX', 'addItemAJAX_callback');
add_action('wp_ajax_no_priv_addItemAJAX', 'addItemAJAX_callback');

3) Ajax Callback and Response

The Ajax callback has security checks and uses wp_send_json_* to handle the response:

function addItemAJAX_callback()
{
    check_ajax_referer( 'my_ajax_validation', 'security' );
    $my_thing = something();
    if( !$my_thing )
        wp_send_json_error( array( 'error' => __( 'Could not retrieve a post.' ) ) );
    else
        wp_send_json_success( $my_thing );
}

4) Finally, the script

It's essential to wrap all jQuery with noConflict mode.
You can pass whatever info you need through the localized object my_handler. We check 3 things from the response:

  • total failure: couldn't reach the callback or didn't pass security
  • partial failure: the callback was reached but returned json_error
  • success: proceed with your thing
jQuery( document ).ready( function( $ ) { 
     var data = {
         action: 'addItemAJAX_callback',
         security: my_handler.ajaxnonce
     };

    $( '#my-submit' ).click( function(e) {
        e.preventDefault();
        $.post( 
            my_handler.ajaxurl, 
            data,                   
            function( response ) {
                // ERROR HANDLING
                if( !response.success ) {
                    // No data came back, maybe a security error
                    if( !response.data )
                        $( '#my-answer' ).html( 'AJAX ERROR: no response' );
                    else
                        $( '#my-answer' ).html( response.data.error );
                }
                else
                    $( '#my-answer' ).html( response.data );
            }
        ); 
    });
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!