Not long ago, Ajax was all the rage - the idea of updating part of a page without actually needing to reload the entire page was awesome, remember?
But it's been a few years and now it's practically the standard - it's hard to think about your favorite web application reloading an entire page to complete a task, isn't it?
Depending on your background, there are a number of different ways to implement Ajax. In this series, we're going to do a very brief overview of what Ajax is, how it works, and then how to properly use it within the WordPress administration dashboard.
Ajax: The Short of It
Ajax is a technology that's typically viewed as an acronym for "Asynchronous JavaScript and XML" but it's really more than that. Generally speaking, Ajax is what we do when we update part of a page (that is, without refreshing the entire thing).
At a high-level, the process looks like this:
- A user performs an event - such as a mouse click - on an element in a page
- The developer has written a function that listens for that event
- When the event occurs, the function sends data from the browser back to the server
- The server then performs an action and/or gathers any requested data and returns it in a specific format
Although data used to be returned in XML, now it's more common to return JSON, HTML fragments, or even basic strings.
On top of that, in the past browsers implemented the underlying facilities for performing Ajax-based functions a bit differently, so building Ajax-enabled applications required a significant amount of code just to handle the variety of browsers.
Luckily, libraries such as jQuery have made this process much easier by providing a level of abstraction that takes away the drudgery of handling cross-browser inconsistencies allowing us to focus solely on sending and receiving data asynchronously.
Since WordPress ships with jQuery, we have the advantage of being able to piggy-back on top of that library for our work. But that's not all - although it's possible to roll your own system for Ajax functionality within WordPress, the platform actually provides a framework for doing it very easily.
Ajax in the WordPress Dashboard
The framework that WordPress provides for introducing Ajax-based functionality is actually a very simple process. First, I'll define it, then we'll look at each step in more detail.
- Create an element that will be used to trigger the Ajax request
- Write JavaScript code to handle the event when the input element's state changes (such as clicked, typed, etc.)
- On the server-side, process the request and prepare a response to return to the browser
- Once again, use JavaScript to handle the response accordingly
Four steps - that's it. Not bad, right? Throughout the remainder of this article, we'll take a look at a practical example of doing exactly this.
Ajax Notification: An Example Plugin for WordPress
In our example, we're going to write a plugin that displays a notification message as soon as the plugin is activated. That's its sole purpose: to simply show that it's active.
Simple? Sure. Pointless? From a functionality aspect, definitely. But we'll be covering a lot of ground that can contribute directly back to practical work: We'll discuss administration notices, nonce values, the WordPress Ajax API, options, and JavaScript-based responses.
Plan the Plugin
Before writing any code, let's plan how the plugin is going to work:
- When the plugin is activated, it should create an option value for storing whether or not the user has selected to hide the message
- When the plugin is deactivated, it should remove the option from the database completely
- The notification message can display a simple message and should be styled with the native WordPress UI
- There should be an element that the user can click to dismiss the message
- If the user opts to hide the message, it should hide without refreshing the page and should be hidden from this point forward
Easy enough, I think. Here's a simple sketch of what the UI of the plugin will look like:
At this point, it's time to write code.
Create the Options
Though the full plugin will be linked at the end of the post, we'll be looking at the plugin as we begin development. Let's setup the basic structure of the plugin so that it's displaying a notification when it's activated.
In order to determine whether or not the user wants to display the notification message, we need to create an option that will store the value. Similarly, we need to delete this value whenever the plugin is deactivated - there's no sense in leaving old data around, right?
To do this, we'll register two hooks: one for activation and one for deactivation.
Let's define the class and the constructor that includes actions for these two methods:
class Ajax_Notification { function __construct() { register_activation_hook( __FILE__, array( &$this, 'activate' ) ); register_deactivation_hook( __FILE__, array( &$this, 'deactivate' ) ); } } new Ajax_Notification();
Of course, nothing will actually happen at this point as we haven't defined the two methods. Let's do that now:
function activate() { add_option( 'hide_ajax_notification', false ); } // end activate function deactivate() { delete_option( 'hide_ajax_notification' ); } // end deactivate
The functions should be relatively clear, but here's a quick explanation of what we're doing:
-
activate
is adding an option to the database with the keyhide_ajax_notification
. Because we want to show the notification until the user says otherwise, we'll set it to false. -
deactivate
simply deletes the option from the database.
Now we just need a message to display.
Create the Notification Message
Let's add another hook into the constructor that will call an action that will actually display a notification message. The updated constructor will look like this:
class Ajax_Notification { function __construct() { register_activation_hook( __FILE__, array( &$this, 'activate' ) ); register_deactivation_hook( __FILE__, array( &$this, 'deactivate' ) ); add_action( 'admin_notices', array( &$this, 'display_admin_notice' ) ); } } new Ajax_Notification();
Of course, nothing will actually happen yet - we need to define a method display_admin_notice
that will be responsible for rendering the message. So let's define that now:
function display_admin_notice() { $html = '<div id="ajax-notification" class="updated">'; $html .= '<p>'; $html .= 'The Ajax Notification example plugin is active. This message will appear until you choose to <a id="dismiss-ajax-notification" href="javascript:;">dismiss it</a>.'; $html .= '</p>'; $html .= '<span id="ajax-notification-nonce" class="hidden">' . wp_create_nonce( 'ajax-notification-nonce' ) . '</span>'; $html .= '</div><!-- /.updated -->'; echo $html; }
Above, we're creating an element that will display a simple message:
The Ajax Notification example plugin is active. This message will appear until you choose to dismiss it.
The message also provides an anchor that will allow users to dismiss the message. The import thing to note about the anchor is this:
- The
href
attribute is an emptyjavascript:;
statement because the message isn't really linking anywhere - The anchor has an ID so that we can easily access the link using JavaScript later in the article
Of course, you could introduce an href
to the anchor in case the user doesn't have JavaScript enabled, but this article is about Ajax so we're assuming that JavaScript is enabled. Progressive enhancement is a whole other topic.
The second thing that you'll notice is that I've included a call to wp_create_nonce
. This is a security measure. When the user clicks on the 'dismiss' anchor, we'll be able to validate that the request is coming from the notification message; otherwise, we can ignore the request.
The method takes in a single value that is used to identify the nonce. In our case, it's ajax-notification-nonce
. We'll be revisiting this value once we begin introducing the Ajax functionality.
Conclusion
By now, you have a fully working - albeit static - plugin. When you activate the plugin, you should see a message similar to the one below:
In the next article, we'll introduce Ajax functionality and we'll end with a checklist of things that all WordPress-based Ajax functionality should have, but in the mean time be sure to check out the following resources:
- Ajax Notification 0.1. A working version of the plugin as developed in this article.
register_activation_hook
deregister_activation_hook
wp_create_nonce
Comments