AJAX (Asynchronous JavaScript and XML) is a powerful technology that allows websites to dynamically update content without reloading the entire page. In WordPress, AJAX is used extensively in plugins and themes to improve user experience and add functionality. In this article, we’ll show you how to register and make an AJAX call in WordPress using the built-in wp_ajax
and wp_ajax_nopriv
hooks.
Step 1: Enqueue the Script
To use AJAX in WordPress, you need to enqueue the script that will handle the AJAX call. You can do this by adding the following code to your theme’s functions.php
file:
add_action( 'wp_enqueue_scripts', 'wp_daily_enqueue_scripts' );
function wp_daily_enqueue_scripts() {
wp_enqueue_script( 'wp_daily_ajax', get_template_directory_uri() . '/js/my-ajax-script.js', array( 'jquery' ), '1.0', true );
wp_localize_script( 'wp_daily_ajax', 'wp_daily_ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}
This code uses the wp_enqueue_script
function to load the my-ajax-script.js
file, which will handle the AJAX call. The wp_localize_script
function is used to pass the AJAX URL to the script, so it knows where to send the AJAX request.
Step 2: Create the AJAX Handler
To make an AJAX call in WordPress, you need to use the built-in wp_ajax
function. This function sends an AJAX request to the WordPress backend and returns the response as a JSON object. When an AJAX request is received by WordPress, it checks the action
parameter to determine which AJAX action to execute. It then calls the callback function that was registered for that action using the add_action
function.
Once you’ve enqueued the script, you need to create the AJAX handler. This is the PHP function that will be called when the AJAX request is made. You can add the following code to your functions.php
file to create the hand
add_action( 'wp_ajax_my_action', 'my_action_callback' );
add_action( 'wp_ajax_nopriv_my_action', 'my_action_callback' );
function my_action_callback() {
// Handle the AJAX request
wp_send_json_success( 'Success!' );
}
This code creates the my_action_callback
function, which will handle the AJAX request. The wp_ajax_my_action
and wp_ajax_nopriv_my_action
actions are used to register the AJAX handler for logged-in and non-logged-in users, respectively.
Step 3: Make the AJAX Request
With the script and handler in place, you can now make the AJAX request. You can do this by adding the following code to your JavaScript file:
jQuery.ajax({
type: 'POST',
url: wp_daily_ajax_object.ajax_url,
data: {
action: 'my_action',
// Additional data to send
},
success: function(response) {
console.log(response);
}
});
This code uses the jQuery.ajax
function to make a POST request to the AJAX URL passed to the script by the wp_localize_script
function. The action
parameter specifies the name of the AJAX action to be called, which in this case is my_action
. The success
function is called when the AJAX request is successful, and outputs the response to the browser console.
wp_ajax vs wp_ajax_nopriv
You may have noticed that we registered two actions in Step 2: wp_ajax_my_action
and wp_ajax_nopriv_my_action
. The wp_ajax
action is used to register AJAX handlers for logged-in users, while the wp_ajax_nopriv
action is used for non-logged-in users.
If you only register an AJAX handler with wp_ajax
, it will only work for logged-in users. Non-logged-in users will receive an 403 Forbidden
error.
Example
Let’s say you want to create a simple AJAX call that takes a number as input and returns its square as output.
First, you need to create a PHP function that will handle the AJAX request. This function will be triggered by a JavaScript event and will return a response in JSON format. Here’s an example:
function wp_daily_ajax_example() {
$response = array(
'message' => 'Hello, world!',
'data' => sqrt((float)$_POST['data']),
);
wp_send_json_success( $response );
}
add_action( 'wp_ajax_wp_daily_ajax_example', 'wp_daily_ajax_example' );
add_action( 'wp_ajax_nopriv_wp_daily_ajax_example', 'wp_daily_ajax_example' );
In this example, we’ve created a function called wp_daily_ajax_example
that takes a POST variable called data
, adds it to an array along with a simple message, and then returns that array as a JSON response using the built-in wp_send_json_success
function.
Now that we have our PHP function set up, we need to create a JavaScript function that will trigger the AJAX call and handle the response. Here’s an example:
jQuery(document).ready(function($) {
$('#wp-daily-ajax-button').on('click', function() {
var data = $('#wp-daily-ajax-input').val();
$.ajax({
url: wp_daily_ajax_object.ajax_url,
type: 'POST',
data: {
action: 'wp_daily_ajax_example',
data: data,
},
success: function(response) {
alert(response.data);
},
error: function(xhr, status, error) {
alert('An error occurred: ' + error);
}
});
});
});
In this example, we’ve added an event listener to a button with an ID of wp-daily-ajax-button
. When the button is clicked, we get the value of an input field with an ID of wp-daily-ajax-input
, and then make an AJAX call using the jQuery $.ajax
function. We pass in the URL of the AJAX handler, the type of request (POST
), the data we want to send to the server (an object with an action
key that matches the PHP function we created earlier, and a data
key with the value of the input field), and finally, two callback functions that handle the response.
In the success
callback function, we simply display the data
value from the response in an alert box. In the error
callback function, we display an error message if the request fails for any reason.
And that’s it! With these two functions in place, you can make AJAX calls in WordPress using jQuery and the built-in wp_ajax_
action hooks. Just be sure to replace the function and variable names with your own, and modify the code to fit your specific needs.
Conclusion
In conclusion, AJAX can be a powerful tool for creating dynamic and interactive WordPress websites. By registering your own AJAX actions and endpoints, you can easily add custom functionality to your website that would not be possible with standard HTML and PHP.
By following the examples in this article, you should now have a good understanding of how to register AJAX actions and endpoints in WordPress, as well as how to handle AJAX requests and send responses.