Hook AJAX in Wordpress

前端 未结 2 1632
情话喂你
情话喂你 2020-12-04 01:22

I have been delving into the world of Javascript and AJAX. I am super close, but for some reason I do not think I am hooking into wordpress ajax functions right. I have pour

2条回答
  •  天命终不由人
    2020-12-04 01:39

    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 );
                }
            ); 
        });
    });
    

提交回复
热议问题