How to Use AJAX in WordPress: Hands-on Guide

When creating and launching a WordPress website, one of the critical things in mind is the user experience. There was a time when, as long as the design was alright, the online audience was captivated enough by static, unchanged pages. But today, the digital space has changed quite drastically. WordPress developers have to opt for revolutionary techniques to improve the user experience and raise impressions. And one such technique is AJAX. 

Using AJAX in WordPress helps you make alterations and fetch and display new content on your web pages without requiring a full page reload. That comes in handy when creating infinite scroll, live search, or loading more items as users scroll down a page. So, how to use AJAX in WordPress? That’s what I have tried to cover through this guide. 

We’ll see how AJAX and PHP enhance the functionality of a WordPress website and how you can use them with and without the plugins. 

But first, let’s see What AJAX is and its pros and cons.

What is AJAX in WordPress Websites?

AJAX (Asynchronous JavaScript and XML) is a web development technique that plays a pivotal role in enhancing WordPress websites’ interactivity, speed, and responsiveness. At its core, AJAX allows web pages to communicate with a server in the background without requiring a full page reload. This asynchronous communication means that specific portions of a web page can be updated dynamically, offering users a smoother and more seamless experience.

This new-age tech is an outstanding tool for WordPress experts looking to create modern, engaging, and user-friendly websites. It empowers WordPress websites to perform various tasks without interrupting users’ browsing flow. Thereby improving overall usability and user satisfaction.

How Does AJAX Work in WordPress Websites?

AJAX enables real-time communication between the client browser and the server. That allows specific parts of a web page to be updated without the need for a full page reload. Here’s how AJAX works in the context of WordPress websites:

#1. Client-Side Interaction

  • The process typically begins when a user interacts with a web page, triggering an event such as clicking a button, submitting a form, or scrolling down a page.
  • JavaScript is used to capture these user actions and initiate an AJAX request.

#2. AJAX Request Initiation

  • When an AJAX request is initiated, JavaScript constructs an HTTP request to be sent to a particular URL on the server. This URL is typically handled by a custom WordPress AJAX handler.
  • The AJAX request includes information like the type of request (GET or POST), any data to be sent to the server (e.g., form inputs), and a callback function to handle the server’s response.

#3. Server-Side Processing

  • On the server side (in WordPress), the AJAX request is intercepted by a PHP function. This function is defined either in your theme’s functions.php file or within a custom plugin.
  • The PHP function processes the request, which can involve database queries, data manipulation, or any other server-side logic necessary to fulfill the request’s purpose.

#4. Server Response

  • After processing the request, the PHP function generates a response. This response can be in various formats, including HTML, JSON, or XML. The format depends on the specific use case.
  • The response is sent back to the client (browser) as the result of the AJAX request.

#5. Client-Side Callback

  • JavaScript on the client side receives the response from the server.
  • The defined callback function processes the server’s response. That may involve updating the DOM (Document Object Model) to display the new content or perform other actions as needed.

#6. Updating the Page

  • With the response data in hand, the client-side JavaScript updates the web page’s content dynamically without causing a full page refresh.
  • Users see the changes or receive feedback based on their interaction, all while staying on the same page.

With AJAX, a WordPress development company can easily create dynamic and responsive features in a website. These features may include real-time content updates, form submissions without page reloads, interactive elements, and more. It ultimately enhances the user experience. 

So, it’s important to handle AJAX requests securely, following best practices to prevent security vulnerabilities. Properly implemented, AJAX can contribute to a more modern and user-friendly WordPress website.

How do AJAX and PHP Enhance the Functionality of Your WordPress Website?

AJAX and PHP can significantly enhance the functionality of your WordPress site by enabling dynamic and interactive features that improve user engagement, usability, and performance. Here’s how these technologies work together to enhance your site:

Real-Time Updates: AJAX allows you to fetch and display real-time updates without refreshing the entire page. When combined with PHP, you can create features like live notifications, chat systems, or dynamic content updates, providing a more engaging user experience.

Efficient Content Loading: AJAX, in tandem with PHP, can be used to load content on demand. For instance, you can implement infinite scrolling, where additional posts or products load as users scroll down the page. That minimizes initial page load times and enhances overall performance.

Interactive Forms: AJAX and PHP can be employed to submit forms without page reloads. It is particularly useful for contact forms, search bars, and user-generated content submissions. Users receive immediate feedback, and PHP processes the form data efficiently.

Content Filtering and Sorting: WordPress experts use AJAX and PHP to create dynamic filters and sorting options for content like products, articles, or portfolios. So users can sort or filter content without navigating to a different page, resulting in a smoother browsing experience.

Interactive Elements: Implementing interactive elements such as modals, pop-ups, image galleries, and tooltips becomes seamless with AJAX and PHP. These elements can be loaded and managed dynamically, enhancing user engagement.

Reduced Server Load: Typically, AJAX requests involve smaller data transfers than full page loads. That reduces the load on your server. PHP processes these requests efficiently, which can lead to improved server performance.

Enhanced User Experience: AJAX and PHP can collectively create a more user-centric experience by reducing wait times and enabling instant interactions. Plus, it offers seamless transitions between different parts of your site.

Improved SEO: While AJAX is known for its dynamic loading capabilities, it’s essential to ensure that critical content remains accessible to search engine crawlers. Properly using AJAX in WordPress with SEO best practices can help maintain good search engine rankings.

Now that you understand how AJAX and PHP enhance the functionality of a WordPress website, we can start the integration process. 

How to Enqueue JavaScript in WordPress?

Before discussing how to use AJAX in WordPress, you must enqueue JavaScript. It’s critical to ensure your scripts are loaded correctly and efficiently.

Here’s the process for enqueuing JavaScript in your WordPress website.

Step 1: Create Your JavaScript File

To start this process, create the JavaScript file containing your custom code with a ‘.js’ file extension. Then, save in the theme or plugin folders of your WordPress file and directory structure

Step 2: Open Your Theme’s functions.php File

Access your WordPress theme’s ‘functions.php’ file. You can find this file in your theme’s directory. It’s typically located at ‘wp-content/themes/your-theme-name/functions.php’.

Step 3: Use the wp_enqueue_script Function

Now, use the ‘wp_enqueue_script’ function to enqueue your JavaScript file. Here’s the basic syntax:

function enqueue_my_script() {
    wp_enqueue_script('script-handle', get_template_directory_uri() . '/path-to-your-js/custom.js', array('dependency'), 'script-version', true);
}
add_action('wp_enqueue_scripts', 'enqueue_my_script');

Here’s a breakdown of this code:

  • ‘script-handle’: This is a unique name or handle for your script. Choose a descriptive and unique name.
  • get_template_directory_uri() . ‘/path-to-your-js/custom.js’: This part specifies the path to your JavaScript file. Make sure to replace ‘path-to-your-script.js’ with the actual path to your script file within your theme directory.
  • array(‘dependency’): If your script depends on other scripts or libraries (e.g., jQuery), you can list them as dependencies in an array. WordPress will ensure that these dependencies are loaded before your script.
  • ‘script-version’: You can specify a version number for your script. It’s a good practice to use versioning to control cache busting.
  • ‘true’: The final parameter sets whether your script should be loaded in the footer of your website (true) or in the header (false). For performance reasons, it’s often recommended to load scripts in the footer, but this can depend on your specific needs.

So if your script handle is ‘my-custom-script’, dependency is ‘jquery’, and script-version is ‘1.0’, the basic syntax will be:

function enqueue_my_script() {
    wp_enqueue_script('my-custom-script', get_template_directory_uri() . '/path-to-your-js/custom.js', array('jquery'), '1.0', true);
}
add_action('wp_enqueue_scripts', 'enqueue_my_script');

Step 4: Hook into the wp_enqueue_scripts Action

Next up, you need to hook your ‘enqueue_my_script’ function into the ‘wp_enqueue_scripts’ action. This action is triggered when WordPress is enqueuing scripts and stylesheets for the front end of your site.

Step 5: Check Your Site

After adding the code to your functions.php file, save the file. When you visit your WordPress site, WordPress will automatically enqueue your JavaScript file. That makes it available for use on your website.

Remember to replace ‘script-handle’, ‘path-to-your-script.js’, ‘dependency’, and ‘script-version’ with your actual script details. Properly enqueuing scripts ensures they are loaded in the correct order and helps prevent conflicts with other scripts on your site.

After enqueuing the JavaScript, we can move on to using AJAX in the WordPress website.

How to Use AJAX in WordPress?

Using AJAX in WordPress involves a series of steps that encompass both client-side JavaScript and server-side PHP code. It helps create dynamic and interactive features on your website.

#1. Client-side JavaScript Setup

Create your JavaScript file (like custom.js) and include it to handle the AJAX request. For this step of the process, you can either use the jQuery library (it’s included in WordPress by default) or another JavaScript library, depending on your preferences. 

In this step, you’ll need to write a JavaScript code for performing the following:

  • Define the AJAX request by including the URL to wp-admin/admin-ajax.php.
  • Make sure you set the action to be taken on the server (the PHP function to execute)
  • Include any data (like form inputs) that you need to send to the server. 
  • Handle the response from the server by specifying a callback function.
jQuery(document).ready(function($) {
    $('#my-button').click(function() {
        $.ajax({
            url: ajaxurl, // The AJAX URL defined by WordPress
            type: 'POST',
            data: {
                action: 'my_ajax_action', // The PHP action to execute
                some_data: 'my_value',     // Any data you want to send
            },
            success: function(response) {
                // Handle the response from the server
                console.log(response);
            },
        });
    });
});

#2. Register AJAX Action in PHP

In this step of using AJAX in WordPress website, you will need to register the PHP function (handling the AJAX request) in your theme’s functions.php or custom plugin file. Specify which actions are to be taken for logged and unlogged-in users through the ‘wp_ajax_’ and ‘wp_ajax_nopriv_’ hooks, respectively.

Also, define the PHP function corresponding to your AJAX action to process the request and generate a response. 

Here’s a sample code for the same:

// For logged-in users
add_action('wp_ajax_my_ajax_action', 'my_ajax_function');
// For non-logged-in users
add_action('wp_ajax_nopriv_my_ajax_action', 'my_ajax_function');
function my_ajax_function() {
    // Process the AJAX request
    $data_received = $_POST['some_data'];
    // Perform actions or queries based on the data
    // Generate a response (e.g., return data in JSON format)
    $response = array('message' => 'Request received with data: ' . $data_received);
    // Send the response
    wp_send_json($response);
    // Always exit to prevent extra output
    exit();
}

#3. Nonce Verification

To enhance security, our WordPress development experts recommend using nonces (number used once) to verify the origin and authenticity of AJAX requests. It will help ensure that no AJAX requests are initiated by malicious actors. 

For nonce verification, you will have to use the function ‘wp_create_nonce()’ to generate a nonce on the client side. Furthermore, the function ‘check_ajax_referer()’ will have to be used on the server side to verify the nonce. 

#4. Testing & Debugging

In this part of the process, thoroughly test your AJAX functionality to ensure it works as expected. Use browser developer tools to monitor network requests and inspect AJAX responses. You can also check the console for any JavaScript errors. Then, you can go on implementing error handling in both the client and server-side code to manage any unexpected situations.

#5. Display AJAX Response

Finally, in your client-side JavaScript, define how to handle and display the AJAX response through the success callback function. In the example above, the response is inserted into an HTML element with “result-container” (from the first step of the process). 

Remember to customize the code according to your particular use case and website requirements. It will help you implement AJAX functionality for dynamic and interactive features effectively. 

How to Make an AJAX Call in WordPress?

Now that you know how to use AJAX in WordPress, let’s see how a WordPress development agency uses it while loading recent blog posts:

Step 1: Create the JavaScript File

First off, create a JavaScript file (like custom.js) in the directory of your WordPress child theme to handle the AJAX request and response. This JS file will contain your AJAX code.

In this example, we’ll name it ‘load-posts.js’. 

jQuery(document).ready(function($) {
    $('#load-posts-button').click(function() {
        $.ajax({
            url: ajax_object.ajaxurl, // This variable is defined by WordPress and points to admin-ajax.php
            type: 'POST',
            data: {
                action: 'load_recent_posts' // The PHP function to execute
            },
            success: function(response) {
                // Replace the content of a div with the received data
                $('#post-list').html(response);
            },
            error: function() {
                console.log('AJAX request failed');
            }
        });
    });
});

Step 2: Register the AJAX Action in functions.php

In this step of using AJAX in WordPress, you’ll need to register the AJAX action (PHP function) in the theme’s functions.php file. You can name this action ‘load_recent_posts’.

// Add this action for logged-in users
add_action('wp_ajax_load_recent_posts', 'load_recent_posts');
// Add this action for non-logged-in users
add_action('wp_ajax_nopriv_load_recent_posts', 'load_recent_posts');
function load_recent_posts() {
    // Query recent posts
    $args = array(
        'post_type' => 'post',
        'posts_per_page' => 5, // Number of posts to retrieve
        'orderby' => 'date',
        'order' => 'DESC',
    );
    $posts = new WP_Query($args);
    if ($posts->have_posts()) {
        while ($posts->have_posts()) {
            $posts->the_post();
            // Output the post title with a link
            echo '<a href="' . get_permalink() . '">' . get_the_title() . '</a><br>';
        }
    } else {
        echo 'No posts found';
    }
    // Always exit to prevent extra output
    exit();
}

Step 3: Create the Button and Target Element in Your Blog Posts

Now, you’ll need to add an HTML element (like a button) and another element (like a ‘div’) within your blog post template or content. The first element will trigger the AJAX request, and the second one will display the loaded posts.

<button id="load-posts-button">Load Recent Posts</button>
<div id="post-list"></div>

Step 4: Enqueue the JavaScript File

Next, as we move into the final stages of using AJAX and PHP in WordPress websites, in the next step, you will enqueue the ‘load-posts.js’ file in your theme’s functions.php file. That will help ensure it’s loaded on the appropriate pages.

function enqueue_my_script() {
    wp_enqueue_script('my-custom-script', get_template_directory_uri() . '/custom.js', array('jquery'), '1.0', true);
    wp_localize_script('my-custom-script', 'ajax_object', array('ajax_url' => admin_url('admin-ajax.php')));
}
add_action('wp_enqueue_scripts', 'enqueue_my_script');

Step 5: Testing

Finally, test your AJAX implementation by visiting a blog post page on your WordPress website. Click the “Load More Posts” button, and it should trigger an AJAX request to fetch and display recent blog posts without reloading the entire page.

Make sure that the JavaScript file and AJAX action are working as expected and that the posts are displayed as intended. This process is a simple answer to how to use AJAX in WordPress websites. However, it can be tricky for those with little to no coding knowledge and experience. If you are one of them, I recommend you get in touch with a WordPress website development company. The experts know how to use AJAX in WordPress to get the best user experience for your website. 

Do you still have doubts about whether or not using AJAX in WordPress would be beneficial? Then I think the next section is just for you.

Which WordPress Plugins Use AJAX?

WordPress development services use AJAX to enhance the websites’ functionality and ensure a smoother user experience. And talking about improving the functionality of WordPress websites, what’s better than plugins? 

You’ll be happy to know that some of the best, most popular WordPress plugins use AJAX to improve their user experience and functionality. 

WooCommerce: With over 5 million active installations, WooCommerce is one of the most popular plugins in WordPress, the leading eCommerce development platform. It uses AJAX extensively for features like adding products to the cart, updating cart contents, and processing checkout steps without page reloads.

Contact Form 7: Another plugin with 5M+ active installations, Contact Form 7 helps you manage and customize the forms on your WordPress website. It incorporates AJAX to handle form submissions asynchronously. That allows the users to submit forms without leaving or refreshing the page.

Jetpack: Created by Automattic, Jetpack is one of the best WordPress plugins for security, performance, backup, marketing, and more. That’s why it’s installed on almost every single WordPress website. This multifunctional plugin uses AJAX for features like related posts, real-time stats, and comment loading. So your users can enjoy dynamic and interactive elements on the website.

WordPress Infinite Scroll and AJAX Pagination: This plugin enables infinite scrolling or AJAX pagination for your WordPress posts. It helps the users load additional content as they scroll down the page.

Mailchimp for WooCommerce: Through this plugin, customers and their purchase data are synced with the Mailchimp account automatically. That makes it easier to send targeted campaigns and automatic follow-ups. With AJAX, the subscriptions can be processed and confirmed without a full page reload.

AJAX Search Lite: AJAX Search Lite adds live search functionality to your WordPress site. That means a live search bar for your website with Google autocomplete and keyword suggestions. So, the users can receive instant search results as they type, thanks to AJAX-powered searching.

W3 Total Cache: It is one of the best-known caching plugins. W3 Total Cache also uses AJAX for its features, like refreshing cached content asynchronously. Plus, it aids in features like purging the cache on demand and clearing it as well. 

Simple Share Buttons Adder: This plugin provides social media sharing buttons that allow users to share content on various social platforms using AJAX to improve the sharing experience.

WPForms: WPForms helps create various types of forms, such as contact forms, registration forms, survey forms, and more. It uses AJAX for various form-related functionalities, including form submissions, error handling, and success messages.

Yoast SEO: The Yoast SEO plugin employs AJAX for features like snippet preview and SEO analysis. It offers real-time feedback and previews for improved SEO optimization. AJAX updates ensure that users are aware of the impact of their changes on the overall SEO score.

These plugins demonstrate the versatility and usefulness of AJAX in WordPress. They enable developers to create dynamic, interactive, and user-friendly features to enhance the functionality and user experience of WordPress websites. 

If you want to use AJAX in WordPress with another plugin, I suggest you opt for our WordPress plugin development services. Our experts will customize your preferred plugin for AJAX call functions to improve the user experience and functionality. 

What are nonces, and why are they important in AJAX requests?
Nonces (number used once) are security tokens used in AJAX requests to verify the authenticity of the request. They help protect your WordPress site from cross-site request forgery (CSRF) attacks. You should include nonce verification in your AJAX requests for security.
What is the difference between 'wp_ajax' and 'wp_ajax_nopriv' hooks in WordPress?
The 'wp_ajax' hook is used for AJAX requests from logged-in users, while the 'wp_ajax_nopriv' hook is used for AJAX requests from non-logged-in users. You should register your AJAX actions with the appropriate hook, depending on your target audience.
Can I use AJAX in WordPress without jQuery?
Yes, you can use AJAX in WordPress without jQuery by using the native JavaScript fetch API or other JavaScript libraries. While jQuery simplifies AJAX implementation, it's not required for AJAX functionality.

Sum Up

Through AJAX and PHP, you can create dynamic, real-time interactions that keep your visitors engaged and satisfied. But unlike a majority of other aspects of this CMS, if you want to know how to use AJAX in WordPress, you need to have a basic understanding and experience of JS and PHP coding. The process involves:

  • Initiating AJAX requests
  • Registering AJAX call actions
  • Handling nonce for security, and,
  • Effectively displaying the AJAX responses on your website 

But on the plus side, using AJAX in WordPress opens up a world of possibilities, from seamless form submissions to dynamic content loading and interactive elements.

So, if you have any more doubts or queries regarding how to use AJAX in WordPress or would like professional help with the same, contact our experts today!

author
Jigar Shah is the Founder of WPWeb Infotech - a leading Web Development Company in India, USA. Being the founder of the company, he takes care of business development activities and handles the execution of the projects. He is Enthusiastic about producing quality content on challenging technical subjects.

Leave a comment