Dev Tip #4: Handling AJAX in WordPress (The Clean Way)

Using AJAX in your plugin can make it feel fast and modern — but if you don’t structure it right, it can become messy and insecure fast.

Here’s how I handle AJAX calls the clean and secure way in WordPress.

1. Enqueue Your Script with ajaxurl

When enqueuing your JavaScript, always localize it with the ajaxurl.

add_action( 'admin_enqueue_scripts', function() {
    wp_enqueue_script( 'my-plugin-admin', plugin_dir_url( __FILE__ ) . 'admin.js', [ 'jquery' ], '1.0', true );
    
    wp_localize_script( 'my-plugin-admin', 'myPlugin', [
        'ajax_url' => admin_url( 'admin-ajax.php' ),
        'nonce'    => wp_create_nonce( 'my_plugin_nonce' ),
    ] );
});

2. The JS Side (Calling AJAX)

jQuery(document).ready(function($) {
    $('#my-button').on('click', function() {
        $.post(myPlugin.ajax_url, {
            action: 'my_plugin_do_something',
            nonce: myPlugin.nonce,
            data: 'SomeValue'
        }, function(response) {
            console.log('Server says:', response);
        });
    });
});

3. The PHP Side (Handling AJAX)

add_action( 'wp_ajax_my_plugin_do_something', 'my_plugin_do_something_callback' );

function my_plugin_do_something_callback() {
    check_ajax_referer( 'my_plugin_nonce', 'nonce' );

    // Capability check if needed
    if ( ! current_user_can( 'manage_options' ) ) {
        wp_send_json_error( 'Not allowed' );
    }

    $value = sanitize_text_field( $_POST['data'] ?? '' );

    // Do something here...

    wp_send_json_success( 'Success! You sent: ' . $value );
}

Bonus: For Frontend Users

If you want AJAX support on the frontend too:

add_action( 'wp_ajax_nopriv_my_plugin_do_something', 'my_plugin_do_something_callback' );

This lets non-logged-in users run the same AJAX handler — great for forms, voting, tracking, etc.

Final Thought

Keep your AJAX code:

  • Localized with nonces
  • Protected with check_ajax_referer()
  • Cleanly separated in JS and PHP
  • Always sanitized and validated

Done right, it makes your plugins feel snappy and pro.


Discover more from WPAnkit

Subscribe to get the latest posts sent to your email.

Comments

Leave a Reply

Discover more from WPAnkit

Subscribe now to keep reading and get access to the full archive.

Continue reading

Discover more from WPAnkit

Subscribe now to keep reading and get access to the full archive.

Continue reading