---
title: "Simple WordPress AJAX Example: A Step-by-Step Guide"
description: "Learn how to use AJAX in WordPress to create dynamic, real-time interactions. This guide covers everything from enqueuing scripts to handling AJAX…"
url: "https://sajdoko.com/blog/simple-wordpress-ajax-example-a-step-by-step-guide/"
language: "en"
content_signal: "ai-train=no, search=yes, ai-input=yes"
---
# Simple WordPress AJAX Example: A Step-by-Step Guide

 18 September 2024·5 minutes read·[Code](https://sajdoko.com/blog/category/wordpress/code/)     

AJAX lets a WordPress page exchange data with the server without a full reload. You can use it for forms, product filters or loading more posts.

 

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.

 

Test the request with valid and invalid input, and check how the page handles a failed response.

  

- [Code](https://sajdoko.com/blog/category/wordpress/code/)
- [WordPress](https://sajdoko.com/blog/category/wordpress/)

   

## Have a project in mind?

 

Write to us and we come back with a concrete estimate within one working day.

  [Contact us →](https://sajdoko.com/contact/)     

## Leave a comment [Cancel](https://sajdoko.com/blog/simple-wordpress-ajax-example-a-step-by-step-guide/?format=markdown#respond)

      

## Recent Posts

- [Fleet management software: what do you need beyond GPS?](https://sajdoko.com/blog/fleet-management-software-requirements-beyond-gps/)
- [Custom CRM Development vs Generic SaaS: The ROI Framework for Growing Enterprises](https://sajdoko.com/blog/custom-crm-development-vs-generic-saas/)
- [Web and Software Development Costs in Albania: The International Buyer’s Strategic Guide](https://sajdoko.com/blog/website-costs-in-albania-international-perspective/)
- [Scaling WooCommerce Performance: Eliminating High-Traffic Checkout Bottlenecks](https://sajdoko.com/blog/scaling-woocommerce-performance-checkout-bottlenecks/)
- [The Hidden Cost of Cheap or “Free” Websites: Why €100 Web Design Costs €3,000 Later](https://sajdoko.com/blog/the-hidden-cost-of-cheap-or-free-websites/)

## Recent Comments

1. Alvaro on [Optimizing and Extending the Livewire Product Filter – Part 4](https://sajdoko.com/blog/optimizing-and-extending-the-livewire-product-filter/#comment-4)
2. [sajdoko](https://sajdoko.com) on [How to Set Up WordPress on localhost Using XAMPP: A Step-by-Step Guide](https://sajdoko.com/blog/how-to-install-wordpress-on-localhost-using-xampp-step-by-step-guide/#comment-3)
3. Roshni on [How to Set Up WordPress on localhost Using XAMPP: A Step-by-Step Guide](https://sajdoko.com/blog/how-to-install-wordpress-on-localhost-using-xampp-step-by-step-guide/#comment-2)
