How to use AJAX in WordPress
AJAX is a mix of HTML, CSS, and JavaScript code that allows you to give data to a script, receive and process the script's response without reloading the page.
Quick summary
AJAX has crept into websites in recent years and has gradually become the technique to develop dynamic, user-friendly, and responsive sites. AJAX is a tool that allows you to change the contents of a page without reloading it in a browser.
While there are several methods to implement AJAX in WordPress – all of which are “right,” in the broadest sense of the term – there is one approach that you should use for several reasons: It is supported by WordPress, it is future-proof, it is highly logical, and it provides you with a variety of possibilities right out of the box.
What is AJAX?
AJAX is a mix of HTML, CSS, and JavaScript code that allows you to give data to a script, receive and process the script’s response without reloading the page.
You could use AJAX to update a user’s profile without having to repeatedly reload the page whenever they submit the form if you’re developing a page on your website where users may edit their profile. When the user hits the button, the information they typed into the form is transferred over AJAX to the processing script, which stores the information and returns for example the string “profile updated.” The data can then be displayed to the user by adding it to the page.
The most important thing to understand about AJAX is how similar it is to what you’re currently doing. If you have a contact form, chances are it is marked up with HTML, has some styles applied to it, and is processed by a PHP script. The only difference between this and AJAX is how the user’s input is sent to the script and then back to the user.
To fully exploit AJAX’s capabilities and get the most out of this tutorial, you must be familiar with JavaScript (jQuery would suffice), HTML, CSS, and PHP. Don’t worry if your JavaScript knowledge is a little shaky; you’ll still be able to grasp the rationale. If you need assistance, please leave a comment and I will do my best to assist you.
How not to use AJAX?
One way that has been around for a while, and one that I used myself back in the day, is to simply include the wp-load.php file at the start of your PHP script. This allows you to access WordPress functionalities, such as detecting the current user, and so on. However, because this is essentially a hack, it is not future-proof. It is far less secure and lacks some of the great features that WordPress provides.
How to use AJAX in WordPress?
Because AJAX is already implemented in the back-end of WordPress, it has been essentially deployed for you. All you have to do is take advantage of the offered functions.
Every AJAX request is sent through the wp-admin folder’s admin-ajax.php file. The fact that this file is called admin–ajax may be confusing. I completely agree, but this is simply how the development process evolved. So, for back-end and user-facing AJAX, we should use admin-ajax.php.
Each request must include at least one piece of data (through the GET or POST method) known as an action. The code in admin-ajax.php produces two hooks based on this action: wp_ajax_an_action and wp_ajax_nopriv_an_action, where an_action is the value of the GET or POST request.
When a function is added to the first hook, it signifies the function will be called if a logged-in user starts the action. You can cater to logged-out users individually using the second hook.
Hot to implement AJAX in WordPress?
As an example, let’s create a simple post-voting counter. First, build and activate an empty plugin. If you need assistance with this step, go to the guide on developing a plugin. Also, locate and open your theme’s single.php file.
How to send the AJAX call?
Let’s make a link that allows readers to give our content a thumbs up or down. If the user has JavaScript enabled, it will utilize it; otherwise, it will follow the link. Add the following code to your single.php file, maybe under the article’s title:
<?php
$votes = get_post_meta( $post->ID, "_votes_counter", true );
$counter = ($votes == "") ? 0 : $votes;
?>
This post was liked <span id="counter"><?= $counter; ?></span> times.
<?php
$nonce = wp_create_nonce( "post_vote_nonce" );
$link = admin_url('admin-ajax.php?action=user_post_vote&post_id='.$post->ID.'&nonce='.$nonce);
echo '<a id="vote" data-nonce="' . $nonce . '" data-post_id="'. $post->ID . '" href="' . $link . '">This post was helpful.</a>';
?>
It should look something like this:
First, we’ll get the value of the votes meta key associated with this post. The overall vote count will be stored in this meta field. Let’s also add validation and make sure that if it doesn’t exist i.e. has an empty string as its value, we display zero.
We’ve also included a standard link here. The only thing additional is a dose of security, in the form of nonces, to ensure there is no foul play. Otherwise, this is just a link to the admin-ajax.php file.
We also include an id to which we will assign a click event and a data attribute that contains the post ID. These will be used to pass the required information to our JavaScript.
How to handle the action without JavaScript?
If you click on this URL right now, you should be routed to the admin-ajax.php script, which should return -1 or 0. This is due to the fact that no function has yet been defined to handle our ‘action‘. So, let’s define it.
Add this code somewhere in your plugin:
add_action("wp_ajax_user_post_vote", "user_post_vote");
add_action("wp_ajax_nopriv_user_post_vote", "user_post_vote");
function user_post_vote() {
if ( !wp_verify_nonce( $_REQUEST['nonce'], "post_vote_nonce")) {
exit("Something is fishy with you.");
}
$counter = get_post_meta( $_REQUEST["post_id"], "_votes_counter", true );
$counter = ( "" == $counter ) ? 0 : $counter;
$new_counter = $counter + 1;
$vote = update_post_meta( $_REQUEST["post_id"], "_votes_counter", $new_counter );
if( false === $vote ) {
$result['request'] = "error";
$result['counter'] = $counter;
}
else {
$result['request'] = "success";
$result['counter'] = $new_counter;
}
if( !empty( $_SERVER['HTTP_X_REQUESTED_WITH'] )
&& 'xmlhttprequest' == strtolower( $_SERVER['HTTP_X_REQUESTED_WITH'] ) ) {
$result = json_encode($result);
echo $result;
}
else {
header( "Location: " . $_SERVER["HTTP_REFERER"] );
}
die();
}
First and foremost, we validated the nonce to ensure that the request is nice and legitimate. If it isn’t, we simply stop the script from running. Otherwise, we proceed and retrieve the vote count from the database, being sure to change it to 0 if there is no vote count. We then increase that by 1 to get the new total.
We add the updated vote count to our article using the update_post_meta() function. Because this function creates the post’s metadata if it doesn’t already exist, we may use it to create as well as update. Because the method returns true if it succeeds and false if it fails, we created an array for both scenarios.
Finally, we determine if the action was started using an AJAX request. If this is the case, we will use the json_encode() method to prepare the array for our code in JavaScript. If the request was done without AJAX, we just redirect the user back to where they came from; clearly, the updated vote total should be displayed. We could alternatively save the array in a cookie or a session variable and deliver it to the user in the same way, but this isn’t necessary for this example.
To guarantee that you get the correct output, always finish your scripts with a die() function. If you don’t include this, you’ll always get a -1 string in addition to the results.
How to handle the action with JavaScript?
We can now begin developing in JavaScript because we’ve handled the user’s action using standard methods. This approach is preferred by many developers because it enables smooth degradation. To make our solution use AJAX, we’ll need to include jQuery as well as our own JavaScript code. Simply go to your plugin and add the following code to implement this WordPress style.
add_action( 'init', 'enqueue_scripts' );
function enqueue_scripts() {
wp_register_script( 'plugin-vote-js', plugin_dir_url( __FILE__ ) . 'js/denar-public.js', array('jquery') );
wp_localize_script( 'plugin-vote-js', 'ajax_url', array( 'ajaxurl' => admin_url( 'admin-ajax.php' )));
wp_enqueue_script( 'plugin-vote-js' );
}
This is how WordPress includes JavaScript files. First, we register the JavaScript file with WordPress so that it is aware of it, so make sure to create the file and place it somewhere in the plugin.
- handle, unique identifier
- the path to the script file
- dependencies – you can find out more baout his here
wp_localize_script() is used to pass variables to use in the script. We will need the admin_url( ‘admin-ajax.php’ ) but you can pass any and as many variables as you want.
After we’ve registered our scripts, we can add them to our pages by enqueuing them. We don’t have to accomplish anything in a certain sequence. WordPress will utilize the proper order depending on the dependencies.
Another way to enqueue the script:
add_action( 'init', 'enqueue_scripts' );
function enqueue_scripts() {
wp_enqueue_script( 'plugin-vote-js', plugin_dir_url( __FILE__ ) . 'js/denar-public.js', array('jquery'), '1.0.0', true );
wp_localize_script( 'plugin-vote-js', 'ajax_url', array( 'ajaxurl' => admin_url( 'admin-ajax.php' )));
}
In your script file add this code:
jQuery(document).ready(function ( $ ) {
$("#vote").click( function(e) {
e.preventDefault();
let post_id = $(this).attr("data-post_id");
let nonce = $(this).attr("data-nonce");
$.ajax({
url: ajax_url.ajax_url,
type: 'POST',
data: { action: "user_post_vote", post_id, nonce },
beforeSend: function () {
// do something before ajax
}
}).success(function (data) {
let response = $.parseJSON(data);
if( response.request === "success" ) {
$("#counter").html(response.counter);
}
else {
alert("Your vote could not be added");
}
});
});
});
All that is left to do is to remove the content of the ‘href‘ attribute and add ‘javascript:void(0)’ instead. Clear the cache and check if the counter is working. It should be increased after every click on the button without refreshing the page.
Summary
This brings us to the end of our little lesson on using AJAX with WordPress. Much more functionality could be added, but the major goal of this post was to demonstrate how to correctly add AJAX functionality to plugins. To summarize, the four phases are as follows:
- Create the AJAX call
- Create a function that will handle the action
- Assign that function to a hook that was already created for us dinamiclly
- Add success and error handlers as need.
Was this post helpful? ( Answers: 1 )
Leave a comment
If you enjoyed this post or have any questions, please leave a comment below. Your feedback is valuable!