Special Offer – WordPress Website

Code WordPress

Simple WordPress AJAX Example: A Step-by-Step Guide

blank

AJAX is a powerful tool in WordPress, allowing for dynamic, real-time interactions on your website without the need to refresh the page. Whether you’re building a contact form, a product filter, or loading posts dynamically, AJAX will provide a smoother, faster experience for your users.

In this guide, we’ll walk through a basic WordPress AJAX example using both JavaScript and PHP. By the end, you’ll be equipped to add custom AJAX functionality to any WordPress site.

What is AJAX in WordPress?

AJAX stands for Asynchronous JavaScript and XML. Essentially, it allows data to be exchanged between the client (browser) and the server without refreshing the entire page. In WordPress, AJAX requests are handled through the admin-ajax.php file. This makes it easy to send data to and from the server with just a few lines of code.

Here’s what we’ll cover in this tutorial:

  • How to properly enqueue JavaScript files in WordPress
  • How to send an AJAX request from the front end
  • How to process the request and return data from the server

 

Step 1: Enqueue Your JavaScript File

The first step in setting up AJAX is to properly enqueue your JavaScript file. In WordPress, this is done using the wp_enqueue_script function. Let’s add the following code to your theme’s functions.php file:


function sajdoko_ajax_enqueue() {

	// Enqueue the JavaScript file on the frontend.
	wp_enqueue_script(
		'sajdoko-ajax-script', // Handle for the script.
		get_template_directory_uri() . '/js/simple-ajax-sajdoko.js', // Path to the script file.
		array('jquery') // Dependencies.
	);

	// Localize script to pass the AJAX URL to JavaScript
	wp_localize_script('sajdoko-ajax-script', 'ajaxurl', admin_url('admin-ajax.php'));
}
// Hook the function to the 'wp_enqueue_scripts' action.
add_action('wp_enqueue_scripts', 'sajdoko_ajax_enqueue');

This code does two things:

  1. Enqueues the JavaScript file simple-ajax-example.js, ensuring it is loaded on the front end.
  2. Uses wp_localize_script to pass the ajaxurl variable to the script, which points to the admin-ajax.php file. This URL is necessary for processing the AJAX request on the server.

 

Step 2: Create the AJAX Request in JavaScript

Next, we need to set up the JavaScript that sends the AJAX request to WordPress. Below is the simple-ajax-example.js file that handles this:


// Wait for the DOM to be fully loaded before executing the script
document.addEventListener("DOMContentLoaded", function () {
    // Define a variable to hold the fruit name
    var fruit = "Banana";

    // Create a new XMLHttpRequest object
    var xhr = new XMLHttpRequest();
    // Initialize a GET request with the URL and query parameters
    xhr.open("GET", ajaxurl + "?action=sajdoko_ajax_request&fruit=" + fruit, true);

    // Define a function to be called when the request completes successfully
    xhr.onload = function () {
        // Check if the status code is in the range of 200-299 (successful responses)
        if (xhr.status >= 200 && xhr.status < 300) {
            // Log the response text to the console
            console.log(xhr.responseText);
        } else {
            // Log an error message with the status code if the request was not successful
            console.log("Error: " + xhr.status);
        }
    };

    // Define a function to be called if the request fails
    xhr.onerror = function () {
        // Log a generic error message to the console
        console.log("Request failed");
    };

    // Send the request
    xhr.send();
});

This JavaScript listens for the page to load, then sends a GET request to the server. It passes the action parameter sajdoko_ajax_request and the fruit value Banana to the server for processing.

The server response is logged to the browser console, or an error message is shown if something goes wrong.

Step 3: Handle the AJAX Request in PHP

Now that the front-end AJAX request is set up, we need to create a PHP function that processes the request and sends a response back. In WordPress, we use the wp_ajax_ hooks to register AJAX actions.


function sajdoko_ajax_request() {

    // The $_REQUEST contains all the data sent via ajax
    if (isset($_REQUEST)) {

        $fruit = $_REQUEST['fruit'];

        // Let's take the data that was sent and do something with it
        if ($fruit == 'Banana') {
            $fruit = 'Apple';
        }

        // Now we'll return it to the javascript function
        // Anything outputted will be returned in the response
	echo 'Your favorite fruit is: ' . $fruit;

        // If you're debugging, it might be useful to see what was sent in the $_REQUEST
        // print_r($_REQUEST);

    }

    // Always die in functions echoing ajax content
    die();
}

add_action('wp_ajax_sajdoko_ajax_request', 'sajdoko_ajax_request');

// If you wanted to also use the function for non-logged in users (in a theme for example)
add_action('wp_ajax_nopriv_sajdoko_ajax_request', 'sajdoko_ajax_request');

The sajdoko_ajax_request function retrieves the fruit parameter sent by the JavaScript file, processes it, and sends a response back. The use of wp_die() is necessary to properly end the AJAX request.

Step 4: Handling Logged-In and Non-Logged-In Users

In WordPress, AJAX requests must be handled differently for logged-in and non-logged-in users. This is why we added two hooks:

  • wp_ajax_sajdoko_ajax_request for logged-in users
  • wp_ajax_nopriv_sajdoko_ajax_request for non-logged-in users

This ensures that your AJAX functionality works for everyone, regardless of whether they are logged into your site or not.

Step 5: Testing Your AJAX Request

With everything set up, it’s time to test your AJAX request. Open your browser’s developer tools (press F12 or Cmd+Opt+I), go to the Console tab, and refresh the page. You should see a message like Your favorite fruit is: Banana appear in the console, which confirms that your AJAX request is working properly!

Expanding the Example

Once you’ve mastered this basic AJAX setup, you can expand it for more advanced use cases. Here are a few ideas:

  • Form Submissions: Use AJAX to submit forms without reloading the page.
  • Load More Posts: Dynamically load more posts when the user scrolls down or clicks a button.
  • Product Filters: Allow users to filter WooCommerce products without refreshing the page.

As always, practice is key. Try integrating AJAX into your own projects to fully understand its potential. If you found this guide helpful, feel free to share it with fellow developers!

Chat on WhatsApp Chat on WhatsApp To top