DEV Community

Cover image for How to Do AJAX in WordPress Correctly: A Complete Guide with jQuery and Vanilla JavaScript
Muhammad Medhat
Muhammad Medhat

Posted on

How to Do AJAX in WordPress Correctly: A Complete Guide with jQuery and Vanilla JavaScript

How to Do AJAX in WordPress Correctly

AJAX (Asynchronous JavaScript and XML) is a technique for making background HTTP requests to the server without reloading the page. In WordPress, AJAX is often used to load data dynamically, process forms, or update content in real time. WordPress has a built-in AJAX handling system via admin-ajax.php that works both in the admin and the front-end — when set up correctly.

In this article, we’ll cover:

  • The basic flow of AJAX in WordPress.
  • Two approaches — jQuery and Vanilla JavaScript.
  • How to properly pass variables from PHP to JavaScript.
  • A quick comparison of both approaches.

1. How WordPress AJAX Works

A standard WordPress AJAX request involves:

  1. JavaScript event triggers a request.
  2. The request is sent to admin-ajax.php with an action parameter.
  3. WordPress executes the matching PHP function via add_action().
  4. The PHP function returns a response.
  5. JavaScript receives the response and updates the DOM.

Official docs: [WordPress AJAX documentation][1].


2. Enqueueing Scripts and Localizing Variables

Whether you use jQuery or Vanilla JS, you first need to enqueue your script in functions.php:

function my_enqueue_scripts() {
    wp_enqueue_script(
        'my-ajax-script',
        get_template_directory_uri() . '/js/my-ajax.js',
        ['jquery'], // remove 'jquery' if using vanilla JS only
        null,
        true
    );

    wp_localize_script('my-ajax-script', 'ajax_object', [
        'ajax_url' => admin_url('admin-ajax.php')
    ]);
}
add_action('wp_enqueue_scripts', 'my_enqueue_scripts');
Enter fullscreen mode Exit fullscreen mode

This wp_localize_script() call makes ajax_object.ajax_url available in your JavaScript file.


💡 Note on ajaxurl vs ajax_object.ajax_url
In the WordPress admin area, there is already a global JavaScript variable called ajaxurl that points to the AJAX handler:

console.log(ajaxurl);
// https://yoursite.com/wp-admin/admin-ajax.php

This variable is only available in the admin by default.
On the front-end, ajaxurl is not automatically defined, so you must pass it yourself.
The standard way to do this is by using wp_localize_script() in PHP:

wp_localize_script('my-ajax-script', 'ajax_object', [
    'ajax_url' => admin_url('admin-ajax.php')
]);

This creates a global object in JavaScript:

var ajax_object = {
    ajax_url: "https://yoursite.com/wp-admin/admin-ajax.php"
};

Summary:

  • Admin pages → You can use ajaxurl directly.
  • Front-end pages → Use a localized variable like ajax_object.ajax_url. Both point to the same endpoint, but their availability depends on context.

3. PHP AJAX Handler

Create the PHP function that will process the request:

function my_ajax_handler() {
    $name = sanitize_text_field($_POST['name']);
    wp_send_json_success("Hello, {$name}!");
}
add_action('wp_ajax_my_action', 'my_ajax_handler');
add_action('wp_ajax_nopriv_my_action', 'my_ajax_handler');
Enter fullscreen mode Exit fullscreen mode
  • wp_ajax_my_action → for logged-in users.
  • wp_ajax_nopriv_my_action → for visitors not logged in.

4. jQuery AJAX Example

If your theme already includes jQuery, AJAX calls are quick to set up:

jQuery(document).ready(function($) {
    $('#myButton').click(function() {
        $.ajax({
            url: ajax_object.ajax_url,
            method: 'POST',
            data: {
                action: 'my_action',
                name: $('#nameInput').val()
            },
            success: function(response) {
                alert(response.data);
            }
        });
    });
});
Enter fullscreen mode Exit fullscreen mode

Pros: Short syntax, good browser support, minimal setup if jQuery is present.


5. Vanilla JavaScript (Fetch API) Example

For modern projects, you can skip jQuery entirely and use the native fetch() API [2]:

document.getElementById('myButton').addEventListener('click', function() {
    const name = document.getElementById('nameInput').value;

    fetch(ajax_object.ajax_url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        body: new URLSearchParams({
            action: 'my_action',
            name: name
        })
    })
    .then(response => response.json())
    .then(data => {
        alert(data.data);
    })
    .catch(error => console.error('Error:', error));
});
Enter fullscreen mode Exit fullscreen mode

Pros: No dependency on jQuery, smaller page size, modern syntax.


6. Comparison: jQuery vs Vanilla JavaScript

Feature / Factor jQuery Method Vanilla JS Method
Ease of Use Very easy if jQuery is already loaded; simple syntax Slightly more verbose; modern syntax but requires understanding of fetch()
Dependencies Requires jQuery library (~90KB minified) No dependencies — built into modern browsers
Browser Support Excellent, including older browsers (IE9+) Modern browsers only (IE not supported without polyfill)
Learning Curve Low, especially for developers familiar with WordPress Moderate — requires ES6+ knowledge
Performance Slightly slower load times due to jQuery overhead Faster initial load (no extra library)
Best For Legacy projects, themes already using jQuery Modern, lightweight projects; performance-focused builds
Example $.ajax({...}) fetch(url, {...})

7. Conclusion

If your theme or plugin already uses jQuery, the jQuery method is fast to implement and compatible with older browsers.
For new, performance-focused builds, vanilla JavaScript with fetch() is the better choice — no extra library required, cleaner dependencies, and a future-proof approach.


References

  1. WordPress Developer Resources. AJAX in Plugins. Available from: https://developer.wordpress.org/plugins/javascript/ajax/
  2. Mozilla Developer Network. Fetch API. Available from: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API
  3. Mozilla Developer Network. URLSearchParams. Available from: https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams

Top comments (1)

Collapse
 
naveed_rehman_a00013810ac profile image
Naveed Rehman

Beautiful!