Advertisement
Plugins

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

by

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:

function my_custom_handler() {
} // end my_custom_handler

Then the corresponding hook would actually look like this:

function my_custom_handler() {
} // end my_custom_handler
add_action( 'wp_ajax_my_custom_handler', 'my_custom_handler' );

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:

function my_custom_handler() {
} // end theme_custom_handler
add_action( 'wp_ajax_nopriv_my_custom_handler', 'my_custom_handler' );

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:

Related Posts
  • Computer Skills
    Automation
    How to Automate Anything with IFTTTIfttt preview
    IFTTT can do so much more than just run pre-made recipes. Here's how you can get it to automate anything you want.Read More…
  • Code
    Creative Coding
    Using WordPress For Web Application Development: Available Features, Part 6: URL Rewriting (or Routes)Application foundation 400
    One of the nicest things about modern web application development frameworks is that they provide a way to generate really clean routes—or URL schemes—that map to the conceptual model of how the application is structured.Read More…
  • Code
    Articles
    WordPress Initialization Hooks: Benefits and Common MistakesHooks
    In programming, initialization of data is important as it's where we setup the prerequisites for the application such as its attributes, its required files and data, its connection to the database, and so on. WordPress itself has a well-defined initialization procedure. Through the page life cycle, WordPress fires a number of actions many of which we've covered in previous articles. To that end, it provides a set of initialization hooks which are naturally used to initialize the application before executing its primary functionality. As plugin and theme developers, it's important to understand the use cases and common mistakes of these initialization hooks, in order to build quality applications. In this article, we are going to take a look at the importance of WordPress initialization hooks and how they are used in various scenarios.Read More…
  • Code
    Creative Coding
    Using WordPress for Web Application Development: Understanding Events, Actions, and FiltersApplication foundation 400
    Throughout this series, we've been taking a look at how WordPress can be used for building web applications. Up to this point, we've established that WordPress is a foundation - rather than a framework - and we've talked a bit about how we need to avoid trying to shoehorn WordPress into another type of design pattern than that of its native type.Read More…
  • Code
    Creative Coding
    Using WordPress for Web Application Development: The Conceptual ModelApplication foundation 400
    With people beginning to realize WordPress' potential as an application foundation rather than just a content management system or a blogging platform, this series is focusing on just how WordPress can be used for such projects.Read More…
  • Code
    Theme Development
    A Guide to the WordPress Theme Customizer: Adding a New SettingTheme customizer 400
    By now, we've taken a look at what the Theme Customizer is, how it works, and the components that are unique to it. We've even discussed how options are serialized into the database so that we may retrieve them later when using our theme. To that end, it's time for us to begin doing our own work with the Theme Customizer. In this article, we're going to take a look at transports, how they work, and the difference in their two primary methods. Additionally, we're going to introduce our own control into one of WordPress' existing sections and see how it works with the various transport models.Read More…