Javascript For WordPress Developers: Using AJAX

wpmu

AJAX, or Asynchronous Javascript and XML, is used to communicate with server-side scripts and allows you to load content dynamically without having to reload the page.

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.

This is the fifth post in our five-part series focusing on JavaScript for WordPress developers. Throughout this series, you’ll learn the basics, but I’ll presume you already have a working knowledge of HTML and CSS. If you need help with these building blocks, take a look at our series about WordPress Development for Beginners.

In the past four tutorials, we’ve looked at the basics of Javascript, jQuery and how to use basic JavaScript in WordPress. In this article, you’ll learn about what AJAX is, what it can be used for, and how to create cool functionality with it in WordPress.

Let’s get started.

Basic AJAX Flow

A common AJAX flow follows the steps below:

  1. Initiate an AJAX call due to a user action
  2. Receive and process the request on the server
  3. Capture the response and perform any required actions via JavaScript

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 script.js, which will contain our JavaScript code. Add the following to the stylesheet:

.gist table { margin-bottom: 0; }

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.

Let’s enqueue the parent’s stylesheet and our JavaScript file in one go:

.gist table { margin-bottom: 0; }

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.

Add an image to your child theme and voila!
Add an image to your child theme and voila!

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:

.gist table { margin-bottom: 0; }

Let’s add our button to the very bottom of all that metadata:

.gist table { margin-bottom: 0; }

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:

.gist table { margin-bottom: 0; }

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.

.gist table { margin-bottom: 0; }

Our little love button, ready to be powered by AJAX.
Our little love button, ready to be powered by AJAX.

Triggering an Action

Finally, we get to our JavaScript! We need to target our button element and detect a click on it. Here’s how to do it:

.gist table { margin-bottom: 0; }

If you click on the button at this stage you should see a JavaScript alert with the text “Love is being given.”

Data Requirements

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.

The wp_localize_script() function was originally intended to translate strings in JavaScript files, which it does well. We can also use it to pass variables to our JavaScript files, in this case the URL of our AJAX file.Add the following code to our existing

Add the following code to our existing ajax_test_scripts() function like so:

.gist table { margin-bottom: 0; }

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 ajaxTest.ajax_url in our JavaScript.

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:

Twenty Sixteen's DOM
Twenty Sixteen’s DOM

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.

.gist table { margin-bottom: 0; }

The Action

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.

.gist table { margin-bottom: 0; }

$.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 $_POST['action'] and $_POST['post_id'].

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.

COURSES

WP Academy – WordPress Wisdom, Bitesized.

Structured e-learning to expand your WordPress and general business horizons. Learn from people like our very own CEO James Farmer with more than a decade’s experience running a WordPress Business!.

LEARN MORE

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_add_love and/or 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:

.gist table { margin-bottom: 0; }

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:

Ajax button popup
Ajax button popup

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.

.gist table { margin-bottom: 0; }

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.

.gist table { margin-bottom: 0; }

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.

Additional Concerns

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.

While this is the final tutorial in JavaScript for WordPress Developers, your learning doesn’t have to stop here! If you would like to continue expanding your JavaScript knowledge, here are some great resources worth checking out:

  • Eloquent JavaScript: Available both digitally and as a hardcopy book, Eloquent JavaScript is a comprehensive and well-structured introduction to JavaScript whether you’re new to the language or you’re an old hat who’s looking for a quick way to get up to speed.
  • W3Schools: It feels like W3Schools has been around forever, and for good reason – it’s an excellent resource for beginners that’s crammed full of examples. Best of all, you can edit the JavaScript examples on the site live and see the results of your changes on the front-end.
  • Codecademy: If you’re an interactive and hands-on learner, popular online code school Codecademy offers a free 10-hour JavaScript course for beginners. It’s divided into eight units that cover concepts including functions, loops, control flow, data structures, and objects. There’s also a final project that involves building a game from scratch – but you’ll have to upgrade to Codecademy Pro to get access.
  • JavaScript Garden: This collection of documentation covers the most quirky parts of the programming language. It offers advice on how to avoid common mistake and subtle bugs, as well as performance issues and bad practices that those new to JavaScript may come across in their learning.
  • Envato tuts+: If you are completely new to JavaScript, don’t know where to start, and need some hand holding, this fantastic article is a great launching pad.
  • JavaScript The Right Way: Despite its name, this one-page guide doesn’t offer instructions on the “the right way” to learn JavaScript, rather it stands as a collection of resources submitted by developers, from information on how to get started and best practices, to tools for testing and frameworks like jQuery and Backbone.js.

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.

Good luck with your JavaScript journey!

Read the original post on  WPMU
About the author

seorocket

Leave a Reply

Be the First to Comment!

Notify of
avatar

wpDiscuz