AJAX and WordPress
When the web moved from HTML4 to HTML5, the rise of AJAX based web applications came along with it. AJAX (which stands for Asynchronous JavaScript and XML) can mean a number of things but in practice it often refers primarily to the client/server interaction where JavaScript can be used to communicate with a server by making calls at various times under various conditions to send and receive data. This can be happening as often as you like in real-time without the user having to navigate to another webpage or refresh their browser (i.e. asynchronously).

What is an example of this? Well, say I wanted to put a stock ticker on my webpage or in my web application. I could use JavaScript to make a call to a service like some stock-market API that will give me quotes on a particular stock, get the data back, and display it in the UI in a visually appealing manner. As these market prices update over time, I can periodically update the quotes that I’m displaying on the page. The format that the server returns data in really depends on the service you are calling. It can often be be XML (as the X in AJAX suggests) but another popular format is JSON. I actually like JSON a bit better, myself. The experience of parsing through everything in code just seems a bit cleaner so if there is the option to have the data you are trying to get returned to you in JSON, I’ll usually opt for that.
Because JavaScript is such a universally cross-platform language capable of running on so many different devices in different environments, this can be a great way for different applications to communicate with each other. The result, hopefully, is to give your users the best experience possible whether they are on desktop, mobile, tablet, or some other crazy device.
In the early part of the 21st century, something else that was and has been absolutely ubiquitous across the internet is WordPress. From it’s humble beginnings of being exclusively web-based blog software, it has transformed into essentially the most popular content management system (CMS) used for running small and medium sized websites or web applications.
In what follows, we can look at how we can undertake merging these 2 things together. We’re basically going to look at how we can send and receive JSON data to a WordPress database and read from and write to the tables within WordPress using AJAX.
So let’s get started…
WordPress Options
Perhaps the most common component of customizing WordPress is using options. When you save custom options to your WordPress database they get stored in the wp_options table. A lot of themes and plugins use these in settings panels where you can customize various aspects of whatever plugin or theme you are using. The way that they save these options is by storing them in the wp_options table. NOTE: Recall that the “wp_” is a prefix that is set in the the wp-config.php file and might vary from installation to to installation depending on how your original WordPress database was set up… but an _options table will always be there regardless of the prefix, and the way that you get and save the options will always be the same.
The way that you save an option is to give it a name…
add_option('my_cool_option', 'hooray');
And you can get each option by reading it, save it to variables, etc.
$hooray = get_option('my_cool_option');
It perhaps is not a particularly efficient arrangement as sometimes you have to read an individual option for customizing every little piece of your entire WordPress stack. As the number of plugins in use and other custom parts of WordPress start to grow, this can potentially cause some slowdown. However, if we were to leverage saving JSON to our wp_options table we can put multiple options into one entry. We’ll still have to pull the JSON down and parse through it, but it may be that this approach leads to less clutter within or WordPress options table. One thing’s for sure. We’ll definitely have that more AJAXy “appy” feel in our WordPress setup.
This article “AJAX in Plugins” on WordPress.org goes over essentially what we want to accomplish. It’s talking about things in the context of plugins, but the same components also apply to theme settings and other areas of WordPress as well.
Creating the Plugin
So let’s start by creating a place in our WordPress admin panel where we can try to get and post some AJAX data using JSON. It’s always a good idea to wrap what we’re doing up in a class and our plugin here will use the same approach. First things first, we’re going to want to add some generic activation and deactivation hooks for our plugin. We’re also going to want to add a menu item to the WordPress admin panel. The page that this menu item will go to will be in the home.php file and we’ll add that in the same directory as our plugin.
<?php
/*
Plugin Name: 9bit Studios WordPress AJAX
Plugin URI: http://www.9bitstudios.com
Description: A plugin demonstrating AJAX in WordPress
Author: 9bit Studios
Version: 1.0.0
Author URI: http://www.9bitstudios.com
*/
class NBS_WordPress_Ajax {
function __construct() {
register_activation_hook(__FILE__, array($this, 'activation'));
register_deactivation_hook(__FILE__, array($this, 'deactivation'));
add_action('admin_menu', array($this,'add_admin_menu'));
}
function activation() {
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
}
function deactivation() {
/* Nothing to do here */
}
function add_admin_menu() {
add_menu_page('WordPress AJAX', 'WordPress AJAX', 'publish_posts', __FILE__, array($this,"home"));
}
function home() {
include('home.php');
}
}
$nbsAjax = new NBS_WordPress_Ajax();
The home.php file won’t be too complicated. Just a couple of places that we will hook our JavaScript to for getting and saving our options, and a panel to show some output.
Next we’re going to want to add our JavaScript/jQuery file. This will also go in the same directory as our plugin. The proper way to do this in WordPress is to use the wp_enqueue_script function. We can use the plugins_url() WordPress function and PHP’s dirname function and __FILE__ constant to specify the path to our plugin directory.
So our plugin now currently looks like this…
<?php
/*
Plugin Name: 9bit Studios WordPress AJAX
Plugin URI: http://www.9bitstudios.com
Description: A plugin demonstrating AJAX in WordPress
Author: 9bit Studios
Version: 1.0.0
Author URI: http://www.9bitstudios.com
*/
class NBS_WordPress_Ajax {
function __construct() {
register_activation_hook(__FILE__, array($this, 'activation'));
register_deactivation_hook(__FILE__, array($this, 'deactivation'));
add_action('admin_footer', array($this, 'cool_options_javascript'));
add_action('admin_menu', array($this,'add_admin_menu'));
}
function activation() {
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
}
function deactivation() {
/* Nothing to do here */
}
function add_admin_menu() {
add_menu_page('WordPress AJAX', 'WordPress AJAX', 'publish_posts', __FILE__, array($this,"home"));
}
function home() {
include('home.php');
}
function cool_options_javascript() {
$pluginDirectory = plugins_url() .'/'. basename(dirname(__FILE__));
wp_enqueue_script("nbs-wp-ajax", $pluginDirectory . '/nbs-wp-ajax.js');
}
}
$nbsAjax = new NBS_WordPress_Ajax();
WordPress AJAX Functions
Now comes the fun part. We’re going to want to create the functions that will handle getting and setting our WordPress options. How does this work in WordPress? Well, as it turns out we can name our function whatever we want, but we have to attach it to a custom action hook and we have to make sure that we prefix our action hook name with “wp_ajax_”. There are a lot of places where WordPress uses specifically named strings as part of its functionality. WordPress is weird like that but that’s how it is and this is one of those cases. We’re going to want to create places to both get and save our options. We need to prefix the string with wp_ajax followed by our_function_name and separate the 2 with an underscore. So our action will be something like “wp_ajax_our_function_name.” So if we were to add these to our plugin it would look something like the following…
<?php
/*
Plugin Name: 9bit Studios WordPress AJAX
Plugin URI: http://www.9bitstudios.com
Description: A plugin demonstrating AJAX in WordPress
Author: 9bit Studios
Version: 1.0.0
Author URI: http://www.9bitstudios.com
*/
class NBS_WordPress_Ajax {
function __construct() {
register_activation_hook(__FILE__, array($this, 'activation'));
register_deactivation_hook(__FILE__, array($this, 'deactivation'));
add_action('admin_menu', array($this,'add_admin_menu'));
add_action('admin_footer', array($this, 'cool_options_javascript'));
add_action('wp_ajax_get_cool_options', array($this, 'get_cool_options'));
add_action('wp_ajax_save_cool_options', array($this, 'save_cool_options'));
}
/**** ACTIVATION ****/
function activation() {
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
}
/**** DEACTIVATION ****/
function deactivation() {
/* Nothing to do here */
}
/**** REGISTER MENU & PAGES ****/
function add_admin_menu() {
add_menu_page('WordPress AJAX', 'WordPress AJAX', 'publish_posts', __FILE__, array($this,"home"));
}
function home() {
include('home.php');
}
function cool_options_javascript() {
$pluginDirectory = plugins_url() .'/'. basename(dirname(__FILE__));
wp_enqueue_script("nbs-wp-ajax", $pluginDirectory . '/nbs-wp-ajax.js');
}
function get_cool_options() {
}
function save_cool_options() {
}
}
$nbsAjax = new NBS_WordPress_Ajax();
As you can see, we’ve used the custom action hook names “wp_ajax_get_cool_options” and “wp_ajax_save_cool_options” that will be used to get an save options when we sent data to them using JavaScript / jQuery a bit later on. Then we give these custom action hooks callback function to run when data get gets sent to WordPress’ core AJAX handling PHP file. We can name these callbacks whatever we want. We don’t need to prefix them with anything.
Now let’s utilize WordPress’s $wpdb class and PHP’s json_encode function to create a way to get and save our data. In WordPress’ AJAX functions, data is going to be available to us via the $_POST variables that will get sent to us via AJAX. We’ll then serialize these variables as a JSON string, and save it to the database using WordPress’ update_option function. Lastly, we’re also going to want to return something back to tell the user that his/her save was successful. So in our callback that saves options, it might look something like the following…
function save_cool_options() {
global $wpdb; // this is how you get access to the database
$itemArray = array(
'name' => $_POST['name'],
'age' => $_POST['age'],
'favorite_color' => $_POST['color'],
);
$saveData = json_encode($itemArray);
update_option('cool_json_option', $saveData);
echo 'true';
die(); // this is required to return a proper result
}
So as we can see, we’re going to save our option value under the name “cool_json_option.”
Our get_cool_options function is goign to be a bit simpler. All we have to do is get the option from the database and return it to the browser as serialized JSON (which is basically the format that it already is).
function get_cool_options() {
global $wpdb; // this is how you get access to the database
$cool_options = get_option('cool_json_option');
echo $cool_options;
die(); // this is required to return a proper result
}
So now that we have our functions all set, we can start calling them with AJAX in JavaScript.
Accessing Our Functions With AJAX
By default, all WordPress AJAX requests are sent to the admin-ajax.php file found in the WordPress core in the wp-admin directory. Fortunately, there is a global variable set by WordPress called “ajaxurl” that points to this file so that we can use in our JavaScript as the URL where we want to send our POST request. So to get or set our options via AJAX we know we’re going to want to send a POST request to a function, but how are we going to tell WordPress which function we want to use to handle our data? Recall, earlier that we gave our action hooks very specific names prefixed by “wp_ajax_.” Well, here is where we’re going to make use of that. This involves sending WordPress an action value in the JSON object we’re going to POST. “action” is the name of the key, and the value will be wp_ajax_our_function_name. So our JSON object that we’re going to send will at least contain the following…
{ action: save_cool_options }
If we wanted to call our function to get our options back from the database, we’d just have to change the “action” value to get_cool_options. We still have to indicate which function we want to call and that’s why we still have to send data to let WordPress know which function we want to use for interchanging data (even if it only involves getting data back).
So to handle this, we’re going to want to send our AJAX requests on the event that gets fired when one of the elements that we defined in our home.php file is clicked. So to do this, we’d create our jQuery file that we’re including in our plugin as follows…
jQuery(document).ready(function($) {
$('#nbs-ajax-get').click(function(){
var mydata = {
action: "get_cool_options",
};
// since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
$.ajax({
type: "POST",
url: ajaxurl,
dataType: "json",
data: mydata,
success: function (data, textStatus, jqXHR) {
var name = data.name;
var age = data.age;
var color = data.favorite_color;
$('#display').html('<p>Name: '+name+' Age: '+age+' Favorite Color: '+color+' </p>');
},
error: function (errorMessage) {
console.log(errorMessage);
}
});
});
$('#nbs-ajax-save').click(function(){
var mydata = {
action: "save_cool_options",
name: 'Bob Jones',
age: 35,
color: 'green'
};
// since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
$.ajax({
type: "POST",
url: ajaxurl,
dataType: "json",
data: mydata,
success: function (data, textStatus, jqXHR) {
if(data === true)
$('#display').html('<p>Options Saved!</p>');
},
error: function (errorMessage) {
console.log(errorMessage);
}
});
});
});
So as we can see on the click events of getting and saving our option, we’re sending our POST requests to ajaxurl (/wp-admin/admin-ajax.php) and then getting data back. Depending on the result, we’re updating the display panel. If we click the button/link to save options and then we open our database and look at the wp_options table, we can see that serialized JSON is saved under the cool_json_option identifier as serialized JSON. If we click the button/link to get these options, assuming all goes well, we can see the panel updated with the values that we specify.
Conclusion
Thus concludes our brief cursory overview of utilizing AJAX in WordPress. Hopefully you found it helpful. Obviously to use this in a more in-depth manner, we’d want to implement more sophisticated error handling and utilization of data in the UI. But hopefully this gives you a good start to being well on your way with using AJAX in WordPress. Take a look at the files(s) below by installing the plugin and playing around with it to see if using JSON in your WordPress admin panel is a good fit for you.
Download Files AJAX, JavaScript, jQuery, WordPress, WordPress plugins





0 Responses to AJAX and WordPress