AJAX (Asynchronous JavaScript and XML) allows WordPress to send or receive data from the server without refreshing the page. This is useful for features like:
- “Load more” buttons
- Real-time form submissions
- Like/favorite buttons
- Live search
- Updating UI based on user input
In WordPress, AJAX requests are routed through admin-ajax.php, which makes handling requests consistent across themes and plugins.
✅ Step 1: Create the AJAX Handler in PHP
Add the following to your theme’s functions.php or your plugin file:
add_action('wp_ajax_training_greet', function () {
wp_send_json_success(['message' => 'Hello logged-in user!']);
});
What’s happening here?
| Part | Meaning |
|---|---|
wp_ajax_training_greet | Hook for logged-in users |
training_greet | Must match the action value in the AJAX request |
wp_send_json_success() | Sends a JSON response WordPress understands |
Supporting Logged-Out Users
If you want visitors (not logged in) to also use this AJAX feature:
add_action('wp_ajax_nopriv_training_greet', function () {
wp_send_json_success(['message' => 'Hello guest!' ]);
});
✅ Step 2: Call the AJAX Action in JavaScript
Here’s a simple fetch() request:
fetch('/wp-admin/admin-ajax.php', {
method: 'POST',
body: new URLSearchParams({ action: 'training_greet' })
})
.then(r => r.json())
.then(data => alert(data.data.message));
What’s happening here?
| Part | Meaning |
|---|---|
/wp-admin/admin-ajax.php | The URL WordPress uses for all AJAX |
action: 'training_greet' | Tells WordPress which PHP function to run |
data.data.message | Contains the message returned from PHP |
✅ Key Takeaways
| Concept | Summary |
|---|---|
| AJAX avoids page reloads | Improves user experience |
Use wp_ajax_ hooks | For logged-in users |
Use wp_ajax_nopriv_ hooks | For logged-out users |
| Always return data in JSON | WordPress utilities like wp_send_json_success() simplify responses |
📌 Example Use Cases to Try Next
- Load More Posts button
- Upvote / Like buttons
- Live Search
- Front-end forms without page reload
