How to Make Modern AJAX Requests in WordPress

AJAX (Asynchronous JavaScript and XML) lets your WordPress site fetch data from the server without reloading the page. This allows you to create fast, dynamic, and interactive user experiences—think live search, dynamic forms, or real-time content updates. In this guide, we’ll walk through how to handle modern AJAX requests in WordPress using best practices.

Why Use AJAX in WordPress?

Traditional WordPress relies heavily on page reloads. Every time a user submits a form or clicks a filter, the entire page refreshes. AJAX solves this by:

  • Loading content dynamically without a page reload.
  • Creating a smoother, faster user experience.
  • Allowing real-time updates for live search, filtering, or dashboards.

Step 1: Enqueue Your Scripts Correctly

The first step is to properly enqueue your JavaScript. WordPress provides wp_enqueue_script() for this. You also need to pass the ajax_url so your script knows where to send requests:


function my_ajax_enqueue_scripts() {
    wp_enqueue_script(
        'my-ajax-script',
        get_template_directory_uri() . '/js/my-ajax.js',
        array('jquery'),
        null,
        true
    );

    wp_localize_script('my-ajax-script', 'my_ajax_obj', array(
        'ajax_url' => admin_url('admin-ajax.php'),
        'nonce'    => wp_create_nonce('my_ajax_nonce')
    ));
}
add_action('wp_enqueue_scripts', 'my_ajax_enqueue_scripts');

Here, wp_localize_script exposes an ajax_url and nonce to your JavaScript file. The nonce adds a layer of security.

Step 2: Create Your JavaScript AJAX Request

In your my-ajax.js file, using jQuery, I personally prefer writing in Vanilla JavaScript, so I’ll add both code snippets:

JQuery:


jQuery(document).ready(function($) {
    $('#my-button').on('click', function(e) {
        e.preventDefault();

        $.ajax({
            url: my_ajax_obj.ajax_url,
            type: 'POST',
            data: {
                action: 'my_custom_action',
                security: my_ajax_obj.nonce,
                someData: $('#my-input').val()
            },
            success: function(response) {
                $('#result').html(response);
            },
            error: function(err) {
                console.log('AJAX error:', err);
            }
        });
    });
});

Modern Fetch API in Vanilla JS:


document.addEventListener("DOMContentLoaded", () => {
    const button = document.getElementById("my-button");
    const input = document.getElementById("my-input");
    const result = document.getElementById("result");

    button.addEventListener("click", (e) => {
        e.preventDefault();

        fetch(my_ajax_obj.ajax_url, {
            method: "POST",
            headers: {
                "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"
            },
            body: new URLSearchParams({
                action: "my_custom_action",
                security: my_ajax_obj.nonce,
                someData: input.value
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                result.innerHTML = data.data; // wp_send_json_success($response)
            } else {
                result.innerHTML = "Something went wrong!";
            }
        })
        .catch(error => console.error("AJAX error:", error));
    });
});

This snippet listens for a button click, sends the input data via AJAX, and updates the page with the server response.

Step 3: Handle the AJAX Request in PHP

Now, we create the PHP function that will handle this request. WordPress uses wp_ajax_ hooks for logged-in users and wp_ajax_nopriv_ for guests:


function my_custom_ajax_handler() {
    check_ajax_referer('my_ajax_nonce', 'security');

    $data = sanitize_text_field($_POST['someData']);
    $response = 'You sent: ' . $data;

    wp_send_json_success($response);
}
add_action('wp_ajax_my_custom_action', 'my_custom_ajax_handler');
add_action('wp_ajax_nopriv_my_custom_action', 'my_custom_ajax_handler');

wp_send_json_success sends a JSON response back to your JavaScript, which you can then use to update your page dynamically.

Step 4: Test It Out

Add a simple HTML form or button to your page:


<input type="text" id="my-input" placeholder="Type something">
<button id="my-button">Send</button>
<div id="result"></div>
  

Click the button and see your input reflected without a page reload.

Modern AJAX in WordPress is all about smooth, dynamic interactions without compromising security. By enqueuing scripts properly, using nonces, and handling requests with wp_ajax hooks, you can create responsive, interactive features that improve user experience.

More Posts