Advertisement
  1. Code
  2. Coding Fundamentals
  3. Game Development

A Primer on Ajax in the WordPress Dashboard - Requesting and Responding

Scroll to top
Read Time: 12 min
This post is part of a series called A Primer On Ajax in the WordPress Dashboard.
A Primer on Ajax in the WordPress Dashboard - Laying the Foundation

In this two part series, we're taking a look at how to properly introduce Ajax-specific functionality into the WordPress Dashboard.

In the first article in the series, we began working on a plugin that displays a notification as soon as it's activated ... but that's it. In this article, we'll add Ajax-enabled functionality that will allow users to dismiss the message and we'll finish up with a working version of the plugin.

Specifically, we're going to cover all of the things necessary on both the server-side and the client-side that are necessary to process an Ajax request and respond appropriately.

Finally, we'll review a checklist of items that all Ajax-based WordPress functionality should have to make sure that you properly employ the API in future projects.


Remember the Nonce

Before we get started, it's important to make sure that you have the nonce value in the function that renders your notification method. For review, here's the function that we included in the first article:

1
2
public function display_admin_notice() {
3
4
	$html = '<div id="ajax-notification" class="updated">';
5
		$html .= '<p>';
6
			$html .= __( 'The Ajax Notification example plugin is active. This message will appear until you choose to <a href="javascript:;" id="dismiss-ajax-notification">dismiss it</a>.', 'ajax-notification' );
7
		$html .= '</p>';
8
		$html .= '<span id="ajax-notification-nonce" class="hidden">' . wp_create_nonce( 'ajax-notification-nonce' ) . '</span>';
9
	$html .= '</div><!-- /.updated -->';
10
11
	echo $html;
12
13
}

Notice that we're rendering the nonce value using wp_create_nonce in a span element having the ID of ajax-notification-nonce. I bring this up for three reasons:

  1. Nonce values provide security measures and are important when you're making any type of request from the front-end to the back-end.
  2. In my experience, this is one of the things that developers most often leave out of their work - this is meant to make sure we have this covered prior to writing any additional code.
  3. The element containing the nonce value needs a specific ID so that we can easily access it using JavaScript when initiating our Ajax request.

With that, let's get to writing the Ajax functionality.


On to Ajax

Building Ajax-based functionality in the WordPress Dashboard typically includes four key points:

  • Some JavaScript functionality that will respond to the user's event and send it to the server
  • A server-side callback function that is responsible for managing the request coming from the browser
  • Server-side functionality that will send the data back to the browser
  • JavaScript functionality responsible for handling the response

Though there's no particular order in which we need to write this code, we'll just go down the list as it's stated above and work through it.

Sending the Request

The JavaScript code for sending the request is relatively boilerplate stuff, but we need to first outline what it is that we're actually going to do:

  • The user decides to dismiss the notification
  • The user clicks on the dismiss anchor that we've provided
  • JavaScript responds to the event when the user clicks on said anchor
  • JavaScript sends a request to the server

We'll write the code incrementally to make sure that it's easy to follow along. First, we'll start by setting up the code after the window has loaded and we'll make sure that the Ajax notification message is present:

1
2
(function ($) {
3
	$(function () {
4
5
		// Check to see if the Ajax Notification is visible; otherwise,

6
		// we won't worry about doing any of this.

7
		if ($('#dismiss-ajax-notification').length > 0) {
8
			// Stuff TODO here...

9
		});
10
	});
11
}(jQuery));

Next, we need to setup an event handler that will fire once the user clicks on the anchor that we've placed in the notification. For this, we need the ID of the message's element - that is, dismiss-ajax-notification.

Because an anchor's default behavior is to try to navigate to its href attribute, we need to also prevent the default action from occurring.

1
2
(function ($) {
3
	"use strict";
4
	$(function () {
5
6
		// Check to see if the Ajax Notification is visible

7
		if ($('#dismiss-ajax-notification').length > 0) {
8
9
			// If so, we need to setup an event handler to trigger it's dismissal

10
			$('#dismiss-ajax-notification').click(function (evt) {
11
12
				evt.preventDefault();
13
				// More TODO here...

14
15
			});
16
17
		} // end if

18
19
	});
20
}(jQuery));

At this point, we're ready to actually send the request to the server. To do this, we'll be using the jQuery post function. We'll be passing it three arguments:

  • The URL of the address to which the request should be sent. This is a global value provided by WordPress. It's stored in the ajaxurl variable
  • The hash of options to send to the server. This includes the action - or the function - to fire on the server and the nonce value for validation
  • The function used to handle the response

Let's write out all of this now (including stubbing out the response function) and then we'll hop over to the server-side code.

1
2
(function ($) {
3
4
	$(function () {
5
6
		// Check to see if the Ajax Notification is visible

7
		if ($('#dismiss-ajax-notification').length > 0) {
8
9
			// If so, we need to setup an event handler to trigger it's dismissal

10
			$('#dismiss-ajax-notification').click(function (evt) {
11
12
				evt.preventDefault();
13
14
				// Initiate a request to the server-side

15
				$.post(ajaxurl, {
16
17
					// The name of the function to fire on the server

18
					action: 'hide_admin_notification',
19
20
					// The nonce value to send for the security check

21
					nonce: $.trim($('#ajax-notification-nonce').text())
22
23
				}, function (response) {
24
25
					// TODO response handler

26
27
				});
28
29
			});
30
31
		} // end if

32
33
	});
34
}(jQuery));

Recall earlier that I said we'd need to know the ID of the field containing the nonce value - that is, ajax-notification-nonce. Notice above that we're grabbing the text value of that element and sending it to the server as the value of the nonce key.

The second thing to notice is that we're sending along an action key that has the value of hide_admin_notification. This is a function that we need to write on the server as it's what will be responsible for actually hiding the notification.

Handling the Request

In our plugin file, we need to create a function that has the name as the action value mentioned above: hide_admin_notification.

As usual, I like to talk about what the function is going to do before writing any code. In this case, here's what needs to be done:

  • We need to make sure the incoming nonce is correct; otherwise, we don't want to execute any code
  • We need to update the option that we created in the first article to set the dismiss to false
  • We need to send a value back to the browser so that it can respond appropriately to the function

Here's the code for making that happen:

1
2
public function hide_admin_notification() {
3
4
	// First, check the nonce to make sure it matches what we created when displaying the message.

5
	// If not, we won't do anything.

6
	if( wp_verify_nonce( $_REQUEST['nonce'], 'ajax-notification-nonce' ) ) {
7
8
		// If the update to the option is successful, send 1 back to the browser;

9
		// Otherwise, send 0.

10
		if( update_option( 'hide_ajax_notification', true ) ) {
11
			die( '1' );
12
		} else {
13
			die( '0' );
14
		} // end if/else

15
16
	} // end if

17
18
}

It's relatively simple, isn't it? The key thing to understand is that we're sending the value of '1' in the context of die if the option is successfully updated; otherwise, we send the value of '0'. This will allow us to read the value in the response on the browser to determine how best to respond.

Obviously, if the returned value is 1, then we can hide the notification.

Before hopping back into the JavaScript, we need to make sure that we wire this function up using the appropriate hook. So, in the plugin's constructor, let's add a line for add_action:

1
2
add_action( 'wp_ajax_hide_admin_notification', array( &$this, 'hide_admin_notification' ) );

The key thing to note here is that the tag for the function is labeled 'wp_ajax_hide_admin_notification'.

If you're working with Ajax in the WordPress dashboard, then your hook must be added with the wp_ajax_ prefix and it should end with the name of the function.

This is easily the second most important thing I see developers miss when working on Ajax-based code.

From here, we're ready to hop back into the client-side code.

Handling the Response

Finally, we're ready to handle the response. This is easy: If the server responds with a 1, then we'll hide; otherwise, we won't do anything.

Granted, the best practice would be to display an error message or some type of feedback to let the user know that something went wrong, but the main point of the article is to demonstrate Ajax in WordPress so we'll simply change out the class name from updated to error.

Here's what needs to be added to the JavaScript source to handle the response:

1
2
function (response) {
3
4
	// If the response was successful (that is, 1 was returned), hide the notification;

5
	// Otherwise, we'll change the class name of the notification

6
	if ('1' === response) {
7
		$('#ajax-notification').fadeOut('slow');
8
	} else {
9
10
		$('#ajax-notification')
11
			.removeClass('updated')
12
			.addClass('error');
13
14
	} // end if

15
16
}

And that's really it. The full JavaScript source should look like this:

1
2
(function ($) {
3
	$(function () {
4
5
		// Check to see if the Ajax Notification is visible

6
		if ($('#dismiss-ajax-notification').length > 0) {
7
8
			// If so, we need to setup an event handler to trigger it's dismissal

9
			$('#dismiss-ajax-notification').click(function (evt) {
10
11
				evt.preventDefault();
12
13
				// Initiate a request to the server-side

14
				$.post(ajaxurl, {
15
16
					// The name of the function to fire on the server

17
					action: 'hide_admin_notification',
18
19
					// The nonce value to send for the security check

20
					nonce: $.trim($('#ajax-notification-nonce').text())
21
22
				}, function (response) {
23
24
					// If the response was successful (that is, 1 was returned), hide the notification;

25
					// Otherwise, we'll change the class name of the notification

26
					if ('1' === response) {
27
						$('#ajax-notification').fadeOut('slow');
28
					} else {
29
30
						$('#ajax-notification')
31
							.removeClass('updated')
32
							.addClass('error');
33
34
					} // end if

35
36
				});
37
38
			});
39
40
		} // end if

41
42
	});
43
}(jQuery));

And the plugin's PHP should look like this:

1
2
/*

3
Plugin Name: Ajax Notification

4
Plugin URI: http://github.com/tommcfarlin/ajax-notification

5
Description: An example plugin used to demonstrate the WordPress Ajax API for a companion article on Envato's WPTuts+ site.

6
Version: 1.0

7
Author: Tom McFarlin

8
Author URI: http://tommcfarlin.com

9
Author Email: tom@tommcfarlin.com

10
License:

11


12
  Copyright 2012 Tom McFarlin (tom@tommcfarlin.com)

13


14
  This program is free software; you can redistribute it and/or modify

15
  it under the terms of the GNU General Public License, version 2, as

16
  published by the Free Software Foundation.

17


18
  This program is distributed in the hope that it will be useful,

19
  but WITHOUT ANY WARRANTY; without even the implied warranty of

20
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the

21
  GNU General Public License for more details.

22


23
  You should have received a copy of the GNU General Public License

24
  along with this program; if not, write to the Free Software

25
  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

26


27
*/
28
29
class Ajax_Notification {
30
31
	/*--------------------------------------------*

32
	 * Constructor

33
	 *--------------------------------------------*/
34
35
	/**

36
	 * Initializes the plugin by setting localization, filters, and administration functions.

37
	 */
38
	function __construct() {
39
40
		load_plugin_textdomain( 'ajax-notification', false, dirname( plugin_basename( __FILE__ ) ) . '/lang' );
41
42
		register_activation_hook( __FILE__, array( &$this, 'activate' ) );
43
		register_deactivation_hook( __FILE__, array( &$this, 'deactivate' ) );
44
45
		add_action( 'admin_enqueue_scripts', array( &$this, 'register_admin_scripts' ) );
46
47
		// Display the admin notice only if it hasn't been hidden

48
	    if( false == get_option( 'hide_ajax_notification' ) ) {
49
		    add_action( 'admin_notices', array( &$this, 'display_admin_notice' ) );
50
	    } // end if

51
52
	    add_action( 'wp_ajax_hide_admin_notification', array( &$this, 'hide_admin_notification' ) );
53
54
	} // end constructor

55
56
	/*--------------------------------------------*

57
	 * Core Functions

58
	 *---------------------------------------------*/
59
60
	/**

61
	 * Upon activation, add a new option used to track whether or not to display the notification.

62
	 */
63
	public function activate() {
64
		add_option( 'hide_ajax_notification', false );
65
	} // end activate

66
67
	/**

68
	 * Upon deactivation, removes the option that was created when the plugin was activated.

69
	 */
70
	public function deactivate() {
71
		delete_option( 'hide_ajax_notification' );
72
	} // end deactivate

73
74
	/**

75
	 * Registers and enqueues admin-specific minified JavaScript.

76
	 */
77
	public function register_admin_scripts() {
78
79
		wp_register_script( 'ajax-notification-admin', plugins_url( 'ajax-notification/js/admin.min.js' ) );
80
		wp_enqueue_script( 'ajax-notification-admin' );
81
82
	} // end register_admin_scripts

83
84
	/**

85
	 * Renders the administration notice. Also renders a hidden nonce used for security when processing the Ajax request.

86
	 */
87
	public function display_admin_notice() {
88
89
    	$html = '<div id="ajax-notification" class="updated">';
90
    		$html .= '<p>';
91
    			$html .= __( 'The Ajax Notification example plugin is active. This message will appear until you choose to <a href="javascript:;" id="dismiss-ajax-notification">dismiss it</a>.', 'ajax-notification' );
92
    		$html .= '</p>';
93
    		$html .= '<span id="ajax-notification-nonce" class="hidden">' . wp_create_nonce( 'ajax-notification-nonce' ) . '</span>';
94
    	$html .= '</div><!-- /.updated -->';
95
96
    	echo $html;
97
98
	} // end display_admin_notice

99
100
	/**

101
	 * JavaScript callback used to hide the administration notice when the 'Dismiss' anchor is clicked on the front end.

102
	 */
103
	public function hide_admin_notification() {
104
105
		// First, check the nonce to make sure it matches what we created when displaying the message.

106
		// If not, we won't do anything.

107
		if( wp_verify_nonce( $_REQUEST['nonce'], 'ajax-notification-nonce' ) ) {
108
109
			// If the update to the option is successful, send 1 back to the browser;

110
			// Otherwise, send 0.

111
			if( update_option( 'hide_ajax_notification', true ) ) {
112
				die( '1' );
113
			} else {
114
				die( '0' );
115
			} // end if/else

116
117
		} // end if

118
119
	} // end hide_admin_notification

120
121
} // end class

122
123
new Ajax_Notification();

Conclusion

You can grab the plugin on GitHub. For reference, be sure to review the following resources:

Advertisement
Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.