A Primer on Ajax in the WordPress Frontend: Understanding the Process

A few articles ago, I gave a primer on Ajax in the WordPress Dashboard, but the comments lead to a discussion for exactly how to do this on the WordPress frontend (and how to do it the right way).

I highly recommend reviewing the previous series to get a feel for where we're going, but in this article, we're going to give a very brief overview of what Ajax is, how it works, how to set it up on the front, and understanding the hooks that WordPress provides.

In the next article, we'll actually build a small project that puts the theory into practice. We'll walk through the source code and we'll also make sure it's available on GitHub, as well.

In the meantime, let's get started reviewing Ajax and the facilities WordPress provides for us.


An Ajax Refresher

At this point in time, Ajax isn't new. In fact, it's hard to find a modern website and/or web application that doesn't already include it, so I'm going to keep this short and to the point.

Generally speaking, Ajax is what allows us to do partial page updates.

This means that we can update a part (or parts) of a page without a user having to refresh the entire page. The lifecycle usually goes something like this:

  • A user triggers an action on the website. Perhaps they click a button, they click a link, or something similar.
  • Without the page refreshing, data is sent to the server.
  • The server processes the data and sends data back.
  • The website then handles that returned data - the response - and updates the page accordingly.
A Primer on Ajax in The WordPress Frontend

Relatively easy to understand, right?


Ajax in WordPress

To understand this process in WordPress, we need to take a look at a few ideas that are more concrete than "the user does something" and "updates the page accordingly."

With that said, most of us are familiar with WordPress' actions, filters, and the general hook system that allows us to, ahem, hook into the WordPress page lifecycle to introduce our own functionality or to process data prior to rendering it. If not, please review the WordPress Hooks - both actions and filters - as this series assumes that you have a level of familiarity with both.

Introducing Ajax into WordPress follows a three step process. It's literally a recipe that can be followed every single time you want to introduce an asynchronous action.

Before looking at said recipe, let me define a couple of terms for the beginners and for those of you who are just getting familiar with Ajax:

  • Event - This means that something happened. Literally, it could mean that the user resized the browser window, the user typed something into an input field, or the user clicked an element.
  • Request - This is what the browser sends to the server. This may contain a set of data that the server needs to process; otherwise, it may just be a signal that the user triggered an event.
  • Event Handler - This is a function that responds to when something happened. This is usually a function that resides on the server and processes the data sent once the above event has fired.
  • Response - This is the data that the event handler sends back to the browser and that is used to update the page.

With that said, here's the recipe that's used to formulate an Ajax request within the context of WordPress (both in the dashboard and in themes or on the frontend):

  1. Introduce an element that the user will click on and setup an event handler using JavaScript to send the request.
  2. Define the event handler in your functions.php file if you're working with a theme or in your plugin.php file if you're working with a plugin.
  3. Write JavaScript to handle the response from the event handler.

Required Actions and Filters

For those of you who read my previous series on Ajax in the Dashboard or who are familiar with Ajax in WordPress, you're likely already familiar with the files and hooks required for implementing Ajax.

Specifically:

  • ajaxurl is the URL provided by WordPress to which we send our request.
  • wp_ajax_my_action is the hook that we use to wire up our event handler.

For a full refresher, be sure to checkout the project on GitHub.

Implementing Ajax on the public-facing side is very similar, but it requires two things:

  • Importing WordPress' Ajax library
  • Two hooks - one of which is the same as mentioned above.

In the next post, we'll spend time looking at how to import WordPress' Ajax library and how to take advantage of it, but the key thing to understand in the rest of the post are the two hooks that are required for setting up our event handlers.

The wp_ajax_my_action Hook

The wp_ajax_my_action hook is the same one that we use when working with Ajax in the Dashboard. It allows us to provide Ajax-enabled actions to users who are logged into WordPress.

This means that you would use this hook if you want to introduce Ajax functionality to users who are administrators, editors, contributors, or members of a site.

Recall that you don't declare wp_ajax_my_action exactly as is. Instead, the suffix 'my_action' should be replaced with your method name. So if you have a function with the signature:

Then the corresponding hook would actually look like this:

Of course, it's not always ideal to restrict functionality to users who are logged into the website.

The wp_ajax_nopriv_my_action Hook

The wp_ajax_nopriv_my_action is very similar to the wp_ajax_my_action hook except for one thing:

You would use this hook if you want to introduce Ajax functionality to users without requiring them to login to the site.

It functions the exact same way and is subject to the exact same rules except for its "target audience," so to speak. This means that you can define your functions like this:

Simple, right?

But there is a security concern here: Because you're opening up certain functions to users who aren't logged in, then key security features such as nonce values won't necessarily work, so you need to be very selective about what you're going to allow people to do if they aren't logged into the site.

As a general rule of thumb, I always say that users who aren't logged into the site should not have access to modify - that is, change, update, delete, or add - any data to the site. Sure, it's a bit restrictive, but this is a matter of the data on your blog, site, or application.

Why sacrifice that?


A Working Example

In the next post, we're going to take a look at a working example that will allow users who are logged into the website to mark off posts that they've read.

In the meantime, be sure to catch up on the following articles as they will help to firm up the upcoming post:

Tags:

Comments

Related Articles