banner-img

How to Use AJAX in WordPress with PHP and JavaScript

Ever wondered how WordPress sites load more content without refreshing the page? That’s the magic of AJAX. It helps create smooth, fast, and dynamic user experiences.

Whether you’re building a live search, filter system, or interactive form, AJAX lets your site fetch and update data without delays. It’s a must-know if you want your site to feel modern and responsive.

If you’re working on a custom feature or plugin, an expert WordPress development agency can help you implement AJAX the right way. Let’s walk through exactly how to use AJAX in WordPress, step by step.

What is AJAX and Why Use it in WordPress?

AJAX (Asynchronous JavaScript and XML) lets a website send and receive data from the server without refreshing the entire page. This makes interactions feel faster and more seamless for users.

In WordPress, AJAX can power things like loading content dynamically, submitting forms, filtering posts, and more – all while staying on the same page. Let’s break it down a bit further.

What is AJAX?

AJAX is not a programming language; it’s a combination of technologies that work together:

  • JavaScript (or jQuery) to trigger events and send requests
  • A server-side script (PHP in WordPress) to handle the logic
  • A way to return the result (typically JSON or HTML)

So when a user clicks a “Load More” button:

  1. JavaScript sends a request to the server.
  2. PHP processes the request and sends back the result.
  3. JavaScript updates the page with the new content – without a full page reload.

Why Use AJAX in WordPress?

Using AJAX improves both performance and user experience. Here’s how:

  • No page reloads: Visitors can interact with your site faster.
  • Dynamic content updates: Load new posts, filter results, or update parts of a form without losing state.
  • Modern interaction: Forms, buttons, search fields, and more feel smoother and more responsive.
  • Better UI/UX: Users stay engaged because the site feels more like a fluid app than a slow-loading webpage.

Here are some real-world features you can build using AJAX in WordPress:

  • Load More Posts: Dynamically append new blog posts when a user clicks a button.
  • Live Search: Display search results as the user types – no refresh needed.
  • Contact Forms: Submit user details and display a success message instantly.
  • Filter Posts by Category or Tag: Let users select filters and reload results without touching the browser’s back button.
  • Like or Vote Buttons: Capture interactions without reloading the content or redirecting.

Whether you’re creating a WordPress theme or building a custom plugin for your WordPress site, AJAX brings a layer of interactivity that modern users expect. Now, let’s explore some ways to implement AJAX in WordPress.

How to Use AJAX in WordPress: 2 Methods

Using AJAX in WordPress isn’t as complicated as it sounds. WordPress offers two main ways to handle AJAX requests, depending on how you want to structure your code and the kind of interaction you need.

The first method uses the traditional admin-ajax.php approach, which is widely supported. The second method uses the more modern and flexible WordPress REST API, which is best for faster and scalable solutions. Let’s look at both methods in detail so you can choose what fits your project best.

Method 1: Using admin-ajax.php (Traditional WordPress AJAX)

The most common way to handle AJAX in WordPress is through a special file called admin-ajax.php. It works for both frontend and backend requests. This method has been around for a long time and remains widely supported and reliable. Here’s how you can implement AJAX using admin-ajax.php.

Step 1: Enqueue JavaScript & Localize AJAX URL

First, enqueue your custom JavaScript file and localize the AJAX URL and nonce so your script knows where to send requests and how to stay secure.

function enqueue_ajax_script() {
    wp_enqueue_script(
        'custom-ajax',
        get_template_directory_uri() . '/js/custom-ajax.js',
        ['jquery'], // dependencies
        null,
        true // load in footer
    );
    wp_localize_script('custom-ajax', 'ajax_obj', [
        'ajaxurl' => admin_url('admin-ajax.php'),
        'nonce'   => wp_create_nonce('ajax_nonce')
    ]);
}
add_action('wp_enqueue_scripts', 'enqueue_ajax_script');

What this does:

  • wp_localize_script() sends PHP data to JavaScript.
  • The nonce helps protect against unauthorized requests.

Step 2: Create the JavaScript AJAX Call

In your JavaScript file (custom-ajax.js), use jQuery’s $.ajax() to send a request to WordPress.

jQuery(document).ready(function($) {
    $('#load-more').on('click', function() {
        $.ajax({
            url: ajax_obj.ajaxurl,
            type: 'POST',
            data: {
                action: 'load_more_posts',
                nonce: ajax_obj.nonce
            },
            success: function(response) {
                if(response.success) {
                    $('#post-container').append(response.data);
                } else {
                    alert('No more posts found.');
                }
            }
        });
    });
});

What this does:

  • The action parameter links the request to the PHP callback.
  • On success, new content is appended without a page reload.

Step 3: Add PHP Callback Function

This function handles the AJAX request, processes data, and sends a response.

function load_more_posts_ajax() {
    check_ajax_referer('ajax_nonce', 'nonce'); // Verify nonce for security
    $query = new WP_Query([
        'post_type' => 'post',
        'posts_per_page' => 3,
        'paged' => 2 // Example: next page of posts
    ]);
    if ($query->have_posts()) {
        ob_start();
        while ($query->have_posts()) {
            $query->the_post();
            echo '<div>' . get_the_title() . '</div>';
        }
        wp_send_json_success(ob_get_clean());
    } else {
        wp_send_json_error('No posts found');
    }
    wp_die(); // Always end AJAX handlers with wp_die()
}
add_action('wp_ajax_load_more_posts', 'load_more_posts_ajax');
add_action('wp_ajax_nopriv_load_more_posts', 'load_more_posts_ajax');

What this does:

  • check_ajax_referer() protects against CSRF attacks.
  • wp_send_json_success() sends a JSON response with the new content.
  • Two hooks register the callback for logged-in and logged-out users.

Step 4: Register AJAX Action Hooks

The last step (done above) connects your PHP callback to the AJAX actions:

add_action('wp_ajax_load_more_posts', 'load_more_posts_ajax');       // For logged-in users
add_action('wp_ajax_nopriv_load_more_posts', 'load_more_posts_ajax'); // For guests

Using admin-ajax.php is straightforward and works well for most use cases. However, it can have performance limitations on very busy sites, which we’ll discuss later.

For now, this method gives you a solid foundation for adding dynamic features to your WordPress site without page reloads.

Method 2: Using the WordPress REST API (Modern AJAX)

The WordPress REST API offers a modern and flexible way to handle AJAX requests. Unlike the traditional admin-ajax.php method, the REST API uses standard HTTP requests with clean URLs and JSON responses. This makes it ideal for building scalable and decoupled applications.

Here’s how to implement AJAX using the REST API.

Step 1: Register a Custom REST API Route

Add the following code to your theme’s functions.php or a custom plugin to create a REST endpoint that filters posts by category.

add_action('rest_api_init', function () {
    register_rest_route('custom/v1', '/filter-posts/', [
        'methods'             => 'GET',
        'callback'            => 'filter_posts_callback',
        'permission_callback' => '__return_true' // public access
    ]);
});
function filter_posts_callback($request) {
    $category = sanitize_text_field($request->get_param('category'));
    $query = new WP_Query([
        'category_name'  => $category,
        'posts_per_page' => 5,
    ]);
    if ($query->have_posts()) {
        $posts = [];
        while ($query->have_posts()) {
            $query->the_post();
            $posts[] = [
                'title' => get_the_title(),
                'link'  => get_permalink(),
            ];
        }
        wp_reset_postdata();
        return rest_ensure_response($posts);
    }
    return new WP_Error('no_posts', 'No posts found', ['status' => 404]);
}

What this does:

  • register_rest_route() defines a new endpoint accessible at /wp-json/custom/v1/filter-posts/.
  • The callback query posts are filtered by the given category.
  • The response returns a simple JSON array of post titles and links.

Step 2: Fetch Data Using JavaScript

Use the JavaScript fetch() method to request filtered posts and display them on the page.

fetch('/wp-json/custom/v1/filter-posts/?category=news')
    .then(response => response.json())
    .then(data => {
        const container = document.getElementById('post-container');
        container.innerHTML = ''; // Clear previous content
        data.forEach(post => {
            const link = document.createElement('a');
            link.href = post.link;
            link.textContent = post.title;
            container.appendChild(link);
        });
    })
    .catch(error => {
        console.error('Error fetching posts:', error);
    });

What this does:

  • The URL includes the category parameter to filter posts.
  • The JSON response is iterated to dynamically create and insert links.

Here are some top benefits of using the WordPress REST API method:

  • Clean, readable URLs and JSON responses.
  • Better performance and scalability on high-traffic sites.
  • Easily integrates with external apps and front-end frameworks.
  • Supports full CRUD operations (create, read, update, delete).

WordPress REST API is a modern way to build interactive features, especially if you want your WordPress site to behave more like a web app. It complements the traditional method and gives you more flexibility for complex projects.

Real-World Use Cases for AJAX in WordPress

AJAX isn’t just a tech buzzword; it powers many practical features that enhance user experience on WordPress sites. Understanding common use cases can help you identify where AJAX fits best in your projects. Here are some typical examples where AJAX makes a big difference:

Instead of pagination content with page reloads, you can load additional posts dynamically when users click a button or scroll down.

Example: A “Load More” button fetches the next batch of posts without refreshing the page, providing a smoother browsing experience.

Display search results instantly as users type, eliminating the need for them to submit a form or wait for a new page.

Example: As users enter keywords, AJAX fetches matching posts or products and updates the result list on the fly.

3. Contact Forms and Form Submissions

Send form data without refreshing the page and show success or error messages instantly.

Example: A contact form that is submitted via AJAX prevents users from losing entered information if validation fails and provides quick feedback.

4. Filtering and Sorting Content

Let visitors filter posts, products, or custom post types by categories, tags, price, or other criteria dynamically.

Example: Clicking filters updates the visible content immediately without page reloads.

5. Interactive Voting and Likes

Capture user interactions like voting or liking a post without interrupting the user experience.

Example: Clicking a “Like” button increases the count instantly and stores the action via AJAX.

Each of these use cases can be implemented using either the traditional admin-ajax.php method or the REST API, depending on your site’s complexity and needs.

AJAX offers many possibilities to make WordPress sites faster and more engaging. With these examples, you’re ready to explore and build dynamic features that keep users coming back.

AJAX Security in WordPress and Common Mistakes to Avoid

When working with AJAX in WordPress, security is just as important as functionality. Since AJAX often involves sending and receiving data between the client and server, it can become a target for attacks if not handled carefully.

Alongside security, avoiding common mistakes will save you from bugs and performance issues. Let’s cover key security practices and common mistakes to watch out for.

Best Security Practices for AJAX in WordPress

Here are some essential security practices you should follow to protect your site while using AJAX.

1. Use Nonces to Verify Requests

Nonces (short for “number used once”) help protect your AJAX endpoints from unauthorized access or malicious requests, such as CSRF (Cross-Site Request Forgery). WordPress provides built-in functions to create, pass, and verify nonces easily.

You should always generate a nonce in PHP, pass it to JavaScript using wp_localize_script(), and then verify it in your PHP handler like this:

// Verify nonce in your PHP callback
check_ajax_referer('ajax_nonce', 'nonce');

If this check fails, the request will be automatically rejected. It ensures only your site’s scripts can make valid requests to your AJAX handler.

2. Sanitize and Validate All Input

Never trust data coming from user inputs, no matter how small or simple it seems. Attackers often try to inject malicious data through AJAX requests. To protect your site, always sanitize and validate every piece of input before using it in your queries or logic. Here’s an example:

$category = sanitize_text_field($_POST['category']);

This simple function ensures that only clean, plain-text input is used in your processing logic, helping prevent common attacks like SQL injection or XSS.

3. Limit Data Exposure

When returning data from your AJAX handlers, only include what’s truly necessary for the front-end interaction. Avoid sending sensitive information or extra internal details that could be misused.

For example, if you’re fetching post titles for a live search, don’t return full post content, author email, or any admin-level metadata. Keep your response minimal and secure.

Common Mistakes to Avoid

Even experienced developers sometimes overlook small but important details when working with AJAX. Here are some common mistakes you should watch out for and how to avoid them.

Not Using Nonces or Skipping Verification

Skipping nonce verification makes your AJAX endpoints vulnerable to CSRF attacks, where malicious users can perform actions on behalf of logged-in users—without their consent.

Always implement and verify nonces to prevent such unauthorized access.

Forgetting to Handle Both Logged-in and Logged-out Users

WordPress separates AJAX action hooks for authenticated and non-authenticated users. If your feature is meant to be accessible to all visitors (like a public search), you must register both hooks:

add_action('wp_ajax_action_name', 'callback_function');
add_action('wp_ajax_nopriv_action_name', 'callback_function');

Skipping the nopriv version will make your AJAX feature work only for logged-in users—often causing confusion and bugs for regular site visitors.

Not Calling wp_die() at the End of AJAX Handlers

After your AJAX handler finishes processing, it’s important to properly terminate the request using wp_die(). Failing to do this may lead to unexpected behavior or send extra unwanted output back to the browser.

Think of it as a clean way to end the response lifecycle after sending your JSON or HTML back.

Sending Raw or Unescaped Output

Never send the raw output directly in your response. It can open your site to XSS attacks, especially if you’re displaying data that users can control. Instead, always sanitize your output or send JSON responses:

wp_send_json_success($data);

Using this function ensures your data is properly encoded and wrapped in a secure response format.

Ignoring Performance Impacts

AJAX runs on the front end but relies heavily on server-side processing. If your callback functions contain slow or heavy queries, it can overload your server, especially on high-traffic sites.

To prevent this, optimize your queries, limit the data being pulled, and use caching where possible, like wp_cache_set() and wp_cache_get()—to reduce unnecessary load.

Securing AJAX endpoints and writing clean, efficient code ensures your WordPress site stays protected while providing dynamic user experiences. Keeping these points in mind will help you build reliable, maintainable AJAX features.

FAQs on Using AJAX in WordPress

How to use AJAX search in WordPress?

To use AJAX search in WordPress, create a search form that triggers an AJAX call on keypress. In your PHP handler, fetch matching posts using WP_Query, return results as JSON, and display them dynamically using JavaScript.

How to insert data using AJAX in WordPress?

To insert data using AJAX in WordPress, send form data to a PHP function using jQuery.ajax(). In the callback, sanitize the input, insert it using wp_insert_post() or database queries, and return a success message with wp_send_json_success().

How to send data to another page using AJAX?

To send data to another page using AJAX, use jQuery.ajax() to send data to a custom PHP handler. Then, redirect users manually using JavaScript (window.location.href) once you get a successful response.

How to load AJAX in WordPress?

To load AJAX in WordPress, enqueue your custom JS file using wp_enqueue_script(), pass the AJAX URL with wp_localize_script(), and hook your PHP function with wp_ajax_ or wp_ajax_nopriv_ as needed.

How to check if a request is AJAX in WordPress?

To check if a request is AJAX in WordPress, use the wp_doing_ajax() function in your PHP callback. It returns true if the request is an AJAX call:
if ( wp_doing_ajax() ) {
    // Handle AJAX logic
}

Final Thoughts

AJAX is a powerful tool that can make your WordPress site faster, more dynamic, and user-friendly. Whether you’re building live search, infinite scroll, or custom forms, AJAX helps load and update data without refreshing the page.

From using admin-ajax.php to the modern REST API method, WordPress gives you flexibility in how you implement AJAX features. Just make sure to follow best practices for security and performance.

If you need help building advanced AJAX features or optimizing your WordPress site, our WordPress development team has got you covered. We build fast, secure, and scalable solutions tailored to your needs. Contact us today to get started on your next project.

Bijal Shah
Bijal Shah

Bijal Shah is a skilled WordPress expert and technical content writer with a passion for making complex topics easy to understand. With her expertise in web development and CMS platforms, Bijal specializes in creating clear, informative, and practical content that helps businesses navigate the digital world.

Leave a Comment

30 days Money Back Guarantee
Secure Online Payment
1 Year of Updates & Support