WordPress AJAX Basics

·

·

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?
PartMeaning
wp_ajax_training_greetHook for logged-in users
training_greetMust 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?
PartMeaning
/wp-admin/admin-ajax.phpThe URL WordPress uses for all AJAX
action: 'training_greet'Tells WordPress which PHP function to run
data.data.messageContains the message returned from PHP

✅ Key Takeaways

ConceptSummary
AJAX avoids page reloadsImproves user experience
Use wp_ajax_ hooksFor logged-in users
Use wp_ajax_nopriv_ hooksFor logged-out users
Always return data in JSONWordPress 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