How to Use AJAX in WordPress? – step by step guide

How to use Ajax in Wordpress

AJAX (Asynchronous JavaScript and XML) allows WordPress websites to load data without refreshing the page. It improves user experience by making interactions faster and more responsive. In this guide, you’ll learn how to use AJAX in WordPress, including setting up AJAX calls, handling requests, and updating content dynamically. Whether you’re working with forms, filters, or live updates, AJAX can enhance your site’s functionality efficiently. Let’s get started with ‘How to use Ajax in WordPress’.

What is AJAX?

AJAX (Asynchronous JavaScript and XML) is a web development technique that allows websites to fetch or send data from the server without reloading the entire page. It helps create dynamic, interactive, and fast-loading websites by updating specific webpage parts in real-time.

Ajax in Simple Word

Suppose, if your client has a “Gallery” page and wants to display 100 images without reloading the page, we can use AJAX to achieve this. Instead of loading all images simultaneously, we can implement a “Load More” button that dynamically fetches additional images. This approach improves page speed and enhances user experience.

With AJAX, we can load multiple images efficiently without affecting performance. Additionally, we can use Fancybox or other image-viewing plugins to display images in a visually appealing way, based on user expectations. This ensures a smooth and interactive gallery experience.

Also, Imagine you’re filling out a form on a website, and as soon as you enter your email, the website checks if it’s already registered—without refreshing the page. That’s AJAX in action! It allows websites to update data smoothly, making interactions quicker and more seamless for users.

Getting started with how to use Ajax in WordPress:

AJAX allows WordPress to send and receive data without refreshing the page, making interactions smoother and faster. To use AJAX in WordPress, the first step is to ensure jQuery is loaded. Since WordPress includes jQuery by default, we can enqueue it in the functions.php file using:

wp_enqueue_script('jquery');
wp_localize_script('Custome-js', 'custom_call', ['ajaxurl' => admin_url('admin-ajax.php'), 'homeurl' => home_url()]); // use this for ajax
PHP

After loading jQuery, we can use AJAX to send GET or POST requests. WordPress provides two important hooks to handle AJAX requests:

wp_localize is most important for work for Ajax. Do not forget to add that to the file.

  1. wp_ajax_ – For handling AJAX requests from logged-in users.
  2. wp_ajax_nopriv_ – For handling AJAX requests from non-logged-in users.

These hooks allow us to process data dynamically without affecting page speed. In the next steps, we will see how to implement AJAX in WordPress effectively.

Note: If you see any error related to jQuery or javascript about the installation then download jQuery and then create a file in a child theme like jquery.min.js and then copy the code from the CDN link and paste the code.

Real Life Example

Suppose you have a Gallery page where you want to display images dynamically with a “Load More” button. To achieve this, we can use the Advanced Custom Fields (ACF) plugin to store and fetch gallery images efficiently.

<?php
$gallery_images = get_field('gallery_images', 'option');
if ($gallery_images): 
?>
    <div id="gallery-container">
        <?php foreach ($gallery_images as $index => $image): ?>
            <div class="gallery-item" <?php echo ($index >= 6) ? 'style="display:none;"' : ''; ?>>
                <img src="<?php echo esc_url($image['url']); ?>" alt="<?php echo esc_attr($image['alt']); ?>">
            </div>
        <?php endforeach; ?>
    </div>

    <?php if (count($gallery_images) > 6): ?>
        <button id="load-more" data-page="1">Load More</button>
    <?php endif; ?>
<?php endif; ?>
PHP

JS Code:

jQuery(document).ready(function ($) {
    $("#load-more").click(function () {
        let button = $(this);
        let page = button.data("page"); 
        let nextPage = page + 1;
        $.ajax({
            url: custom_call.ajaxurl,
            type: "POST",
            dataType: "json",
            data: {
                action: "load_more_images",
                page: page,
            },
            beforeSend: function () {
                button.text("Loading..."); 
            },
            success: function (response) {
                if (response.success && response.data.length > 0) {
                    let imagesHtml = "";
                    $.each(response.data, function (index, image) {
                        imagesHtml += '<div class="gallery-item">';
                        imagesHtml += '<img src="' + image.url + '" alt="' + image.alt + '">';
                        imagesHtml += '</div>';
                    });
                    $("#gallery-container").append(imagesHtml);
                    button.data("page", nextPage);
                    button.text("Load More");
                } else {
                    button.hide(); 
                }
            }
        });
    });
});
PHP

Functions.php File:

function enqueue_gallery_scripts() {
    wp_enqueue_script('jquery');
    wp_enqueue_script('gallery-Custome-js', get_template_directory_uri() . '/assets/js/custom.js', array(), '20151215', true);
    wp_localize_script('gallery-Custome-js', 'custom_call', ['ajaxurl' => admin_url('admin-ajax.php'), 'homeurl' => home_url()]);
}
add_action('wp_enqueue_scripts', 'enqueue_gallery_scripts');
function load_more_images() {
    $page = isset($_POST['page']) ? intval($_POST['page']) : 1;
    $images_per_page = 6;
    $offset = $page * $images_per_page;
    $gallery_images = get_field('gallery_images', 'option');
    $response = array();
    if ($gallery_images) {
        $total_images = count($gallery_images);
        for ($i = $offset; $i < ($offset + $images_per_page) && $i < $total_images; $i++) {
            $image = $gallery_images[$i];
            $response[] = array(
                'url' => esc_url($image['url']),
                'alt' => esc_attr($image['alt']),
            );
        }
        wp_send_json_success($response);
    } else {
        wp_send_json_success(array()); 
    }
    wp_die(); 
}
add_action('wp_ajax_load_more_images', 'load_more_images');
add_action('wp_ajax_nopriv_load_more_images', 'load_more_images');
PHP

How AJAX “Load More” Works in WordPress – Simple Explanation

When using AJAX to load more images in WordPress, we follow a step-by-step process. This guide will help you understand how it works in a very simple way.

Step 1: Clicking the “Load More” Button

  • When the user clicks the “Load More” button, an event triggers in JavaScript (jQuery).
  • The button has an attribute called data-page, which tells us which page is currently being displayed.
  • We use this value to load the next set of images when the button is clicked.
  • Since page 1 is already visible, the next page should be page 2, so we increase the page number by 1.

Step 2: Sending an AJAX Request

  • AJAX is used to send data to the server without reloading the page.
  • We tell AJAX:
    1. Where to send the request → The admin-ajax.php file in WordPress.
    2. How to send the request → We use the POST method to send data.
    3. What data to send → The current page number and the action name (which function to run in PHP).
  • Before sending the request, we change the button text to “Loading…” so the user knows something is happening.

Step 3: Handling the AJAX Request in WordPress (PHP Side)

  • When the request reaches functions.php, we get the page number using $_POST['page'].
  • Now, we need to fetch the images for the next page from the ACF gallery field.
  • We decide how many images to load per page (for example, 6 images).
  • Using a loop, we collect the next set of images and send them back as a response.
  • We used wp_send_json_success() to send the images in JSON format.
  • We also use wp_die(); it to properly end the function.

Step 4: Receiving the Response and Displaying Images

  • When the response comes back to JavaScript, we check if images were received.
  • If new images are found, we add them to the gallery using append().
  • We also update the data-page value to the next page number.
  • If no more images are left, we hide the “Load More” button to prevent extra requests.

Step 5: Checking the Request and Response

  • You can check if data is sent and received correctly by opening the browser’s developer tools.
  • Press F12 or right-click on the page and choose Inspect → Go to Network → Check Payload and Response.
  • This will help you see what data was sent and received.

Output:

Output for how to use ajax in wordpress

Related Posts:

>>What is High-Performance Order Storage in WooCommerce?

>>How to Extend WooCommerce REST API

Conclusion: How to Use AJAX in WordPress

Using AJAX in WordPress is a powerful way to improve user experience by loading content dynamically without refreshing the page. Whether you’re implementing a Load More button for images or fetching new posts, AJAX makes the process seamless and efficient. By following the steps outlined, you can enhance website performance, reduce load times, and keep users engaged. Always ensure proper security measures to prevent vulnerabilities, and optimize the AJAX requests for better speed.

With this approach, you can create interactive and fast-loading WordPress websites that offer a smooth browsing experience. Let me know if you have any doubts about Ajax or any WordPress topic. You can comment down in comment box🚀

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.