Say, for example, that you’re building a website for a local charity and you want to encourage a positive vibe. You could add a button titled “Show some love!” with a counter on the homepage and, thanks to AJAX, every time the button is pressed the counter would increment without reloading the page.
This is the example we’re going to build in today’s tutorial.
Let’s get started.
Basic AJAX Flow
A common AJAX flow follows the steps below:
- Initiate an AJAX call due to a user action
- Receive and process the request on the server
Setting Up a New Theme Environment
Let’s set this up in WordPress. Our first example will show a simple pop-up containing the number of comments a post has when we click on the title. We’ll use a child theme based on the default Twenty Sixteen WordPress theme so we all start from the same base.
Here’s what you need to do: Create a new folder in the themes directory in your WordPress install and name it “ajax-test.” Within the directory, create two files:
style.css, which is required by WordPress, and
functions.php, which we’ll use to add our own functionality, and finally
The stylesheet from the parent theme needs to be loaded by the child theme. Once upon a time this was done by importing it from the child theme’s CSS file but the recommended way of achieving it now is by enqueueing it. If you need a refresher on enqueing, have another read over part four in this series.
If you feel you have the energy to go one step further, find a nice image, crop it to 880px by 660px and place it in the child theme’s folder, and then name it it
screenshot.png. It will show up in the Appearance section when you’re ready to activate the theme.
Since this child theme is based on Twenty Sixteen and we haven’t modified anything (yet!), the site should look exactly as if it were running the parent theme.
Adding a Button
To get started, let’s add the “Show some love!” button. A great place to put it would be the sidebar of posts in the theme.
After some research, it turns out that the sidebar is created by a function named
twentysixteen_entry_meta() which resides in
inc/template-tags.php in the parent theme.
This function is “pluggable,” which means that we can modify it by defining it in our own functions.php file. The first step of this is to copy-paste the whole function into our own functions.php file:
Let’s add our button to the very bottom of all that metadata:
Let’s walkthrough what all that code means.
The first line retrieves the number of loves the post has received. In some cases, this data will not exist, i.e. when no one has clicked the button yet. Due to this, we use the second line in the code to set the value to
0 if the value is empty.
The third line outputs the button, which consists of a span containing an image and the number of loves. I’ve left the source of the image empty because I want to use an SVG in there. You could use base64 encoded SVG to create an image inline. This saves you requests and will make your website perform better.
I used this free little heart image, clicking on the
SVG - Base64 link below it. Copy-paste the code you receive into the image source like so:
I also used a little CSS to style the button and give it a hover effect. It’s not very obvious that this is a button, but it will do for our simple test.
Triggering an Action
Instead of that text we need to trigger an AJAX call. Before we write our code, let’s figure out what we need to send.
The AJAX URL
First and foremost, we need a place to send the data. The place we send the data to will process the data and respond to the call. WordPress has a location built in to handle AJAX calls, which we can use: the
admin-ajax.php file within
wp-admin. We have no way to add this URL to our script (short of hardcoding it, which is out of the question) so we’ll use some WordPress trickery.
Add the following code to our existing
ajax_test_scripts() function like so:
The result of this will be an object named
ajaxTest , which will contain the array given in the final parameter as properties. To grab the value of
ajax_url we can use
The Post ID
We’ll be sending arbitrary data like the post’s ID (which we’ll use to identify the post we’re adding love to). This can be retrieved from the DOM. Take a look at the structure used in the Twenty Sixteen theme below:
Our button has an “article” element as one of its ancestors. This element has the class
post and contains the numeric ID in the ID property. While not the most elegant solution we can grab the ID from there.
WordPress also requires that we send a parameter named action. Since all actions will be sent to
admin-ajax we need a way to differentiate between them – this is what this parameter is used for.
Sending An AJAX Request
We can now put everything together. We need to create an AJAX call to
wp-admin/admin-ajax.php that contains the post ID and an action. Here’s how.
$.ajax() is the function used which takes a bunch of parameters.
url contains the target which is currently our website’s
ajax-url.php file. The type is set to
post which should be familiar from HTML forms. The data parameter is an object that contains key-value pairs we want to send to the server. Later on, we’ll be able to read them with
The success parameter is a function, which will run when the AJAX call has been completed. We’ll show a simple alert that shows “Success! The new count is” with our response tacked on the end.
Processing the Request
Normally you would need to edit the
admin-ajax.php file since the request is sent there. This is a core file though, which means that editing is a big no-no. WordPress allows you to precess AJAX calls using hooks and the action parameter. The pattern is the following:
If you named your action ‘add_love’, you need to attach a function (names anyway you like) to a hook named
wp_ajax_nopriv_add_love. The nopriv one fires for logged out users, the one without it fires for logged in users only. In our case we’d like both. As a quick test, let’s hard-code a response:
We attached our function to both hooks, echoed
4 and then used the
die() function. This is required in WordPress, otherwise you will receive a
0 at the end of every response. If you click the button now you should see the following:
To get the actual number of “loves” all we need to do is retrieve the current number, increment it by one, save it to the database and echo the new number.
If you click the button now you should see the popup showing you “1”. If you refresh the page you should see the new number being shown. Clicking the button will return 2. All we need to do now is make sure the number is reflected in the UI immediately.
Performing UI Changes Using the Response
This part seems easy (because it is), but is usually the most difficult to get right – more on this later. For now all we need to do is pinpoint the element that contains the current number and change its content to the response.
I’ve only added two lines to our previous JS code. On line 5, I store the element that contains the number in the
$number variable. On line 14, I modify the text of this element to contain the response, which is the new love count.
AJAX isn’t too difficult on the surface but it gets very difficult when trying to create a nice UI. Sending data, processing it and creating a response is almost trivial but here are some issues regarding the usage of the response that you may not have thought of:
- What happens if someone accidentally double-clicks?
- What if someone abuses the button and presses it continuously?
- If the response takes a long time to arrive the user is left wondering.
- The number change may not be too obvious.
- The button itself is not obviously a button.
Solving these issues is not really within the scope of this tutorial. Some of this can be learned reading other tutorials, but you partly need to rely on your experience to create a smooth and understandable UI for your actions.
Safety is another huge concern. In this simple love example it may not be obvious but you might want to build a button for admins that deletes posts. All actions should be protected by nonces.
WordPress and the Power of AJAX
Creating smooth interfaces and useful user actions is easy using AJAX. You’ll need to send a request, which contains some data, process it on the server, send back a response and use the response to initiate UI changes.
The real challenge of AJAX, though, is using it responsibly and making sure that your UI is air-tight before, during and after your action has been performed.
As with learning any new skill, the more you read and practice, the easier learning will become and the sooner you’ll be proficient in another language.