Ajax in WordPress Plugin


Introduction

Ajax (Asynchronous JavaScript And XML) is a technology that allows a web page to update some of its information without a full page reload. It is used in the Administration sections of WordPress for auto-save of post edits, adding new categories, and other purposes. Some WordPress Plugins also use AJAX for things like voting on post ratings and map refreshes.

This article, aimed at plugin developers, describes how to add Ajax to a plugin. Before reading this article, you should be familiar with the following:

* Ajax – Overview of the technology
* Writing a Plugin – How to write a plugin
* Plugin API – Filters and actions – what they are and how to use them
* How to add HTML to the appropriate WordPress page, post, or screen — for instance, if you want to add Ajax to administration screens you create, you will need to understand how to add administration menus to WordPress; if you want to add Ajax to the display of a single post, you’ll need to figure out the right filters and actions to add HTML to that spot on viewer-facing blog screens. This article does not cover these topics.
* You will also need to know something about client-side JavaScript programming, PHP programming, and HTML, in order to use Ajax in WordPress.

It turns out that the techniques for adding Ajax to a plugin are quite different, depending on whether you want the Ajax functionality to be part of the WordPress administration screens, or to appear on the viewer-facing side of WordPress. So, this article treats those two possibilities separately (after discussing common considerations).

Ajax Implementation Basics

There are three steps in an Ajax request, in general:

1. The user does something (such as clicking or dragging the mouse), and JavaScript embedded in the HTML of the web page responds by composing a “request” and sending it to a special URL on the web server. Due to security restrictions, the URL the request goes to must be on the same web site that the file containing the JavaScript came from.
2. A script or program on the web server (in WordPress, this will generally be one or more PHP functions) processes the request and sends information back to the browser.
3. The returned information is displayed using JavaScript.

Unfortunately, much of Ajax is JavaScript, which runs in the user’s web browser, and the different web browsers have not all implemented the Ajax calls and responses in the same manner. So, to make things easier, most Ajax developers choose to use a tested cross-browser library that wraps the particular browser idiosyncracies in a standard class with a documented API. In this article, we’ll use one such library, SACK (Simple Ajax Code-Kit), which is included in WordPress. The Further Reading section (see bottom of page) has several references for how to use JQuery to do AJAX — JQuery is another library included in WordPress, and the concepts are pretty much the same, but the syntax is a bit different.

So, we’ll need to make sure both the SACK library and the JavaScript functions that compose the Ajax request get included in the HTML head section of the web page where the Ajax request will take place; the sections below will show how to do that for both the administration and viewer-facing sides of WordPress.

When creating an Ajax request using the SACK library, we’ll need to supply the following information; the sections below will fill in the details of what this information should be for the administration side and the viewer-facing side:

* Request URL: The URL on the server that will process the Ajax request.
* Custom request variables: SACK allows us to set arbitrary request variables, which are sent via POST or GET to the server. Cookie information can also be sent.
* What to do if there is an error: a JavaScript function to call if there is an Ajax error.

By default, SACK assumes that the returned information from the server is JavaScript code, which is executed when it comes in (asynchronously). In the examples below, we’ll use this default behavior, so the PHP functions that are processing Ajax requests will need to compose their results into JavaScript commands. If you want to do something else with the returned information in your plugin, you might want to visit the SACK Project Home Page, download the zip file, and read the documentation, because there are definitely other possibilities.

One other detail is that the PHP function that processes the Ajax request should use the PHP die function at the end.

Ajax on the Administration Side

Since Ajax is already built into the core WordPress administration screens, adding more administration-side Ajax functionality to your plugin is fairly straightforward, and this section describes how to do it. As mentioned above, if you want to use Ajax on the blog-viewer-facing side of WordPress, you can completely skip this section of the article.

Here’s a short example. All this will be in one file.

First, add some javascript that will trigger the AJAX request:

jQuery(document).ready(function($) {

var data = {
action: ‘my_special_action’,
whatever: 1234
};

// since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
jQuery.post(ajaxurl, data, function(response) {
alert(‘Got this from the server: ‘ + response);
});
});

<?php
}

Then, set up a PHP function that will handle that request:

<?php

add_action('wp_ajax_my_special_action', 'my_action_callback');

function my_action_callback() {
global $wpdb; // this is how you get access to the database

$whatever = $_POST['whatever'];

$whatever += 10;

echo $whatever;

die();
}

That's it! You will need to add a few details, such as error checking and verifying that the request came from the right place ( using check_ajax_referer() ), but hopefully the example above will be enough to get you started on your own administration-side Ajax plugin.
NOTE: Since Version 2.8, The javascript global variable ajaxurl can be used in case you want to seperate your javascript code from php files into javascript only files.

Ajax on the Viewer-Facing Side

As of WordPress 2.8, there is a new hook similar to 'wp_ajax_my_action':

'wp_ajax_nopriv_my_action' executes for users that are not logged in.

So, if you want it to fire for both visitors and logged-in users, you can do this:

add_action('wp_ajax_my_action', 'my_action_callback');
add_action('wp_ajax_nopriv_my_action', 'my_action_callback');

Note: In WP 2.8, if a user is not logged in ('wp_ajax_nopriv_my_action'), then GET requests are ignored (and return -1). This bug was fixed in WP 2.9.
Note 2: Unlike on the admin side, the "ajaxurl" javascript variable does not get automatically defined for you. Use this PHP code to generate the URL you need to call instead:

echo admin_url('admin-ajax.php');

Ajax on the Viewer-Facing Side ( WordPress 2.6 , 2.7, 2.8 )

Implementing Ajax on the viewer-facing side in older versions of WordPress is slightly more ad-hoc than doing Ajax on the administration side and this section describes how to do it.

As an example, let's consider a plugin that allows a blog viewer to vote on or rate something (which could be a generic poll plugin, a post rating plugin, or something else like that). When the blog viewer submits a vote, we want the submission to go via Ajax, so that the viewer doesn't have to wait for the page to refresh; after the vote is registered, we'll want to update the running vote total display. For this example, we'll assume the voting and display are text-based, for simplicity, and we'll assume you've either edited the theme or used a WordPress filter or action to add HTML to the appropriate WordPress viewer-facing screen. The added HTML will look something like this:

Your vote:

(previous results output from your PHP function)

Next, we need to define the JavaScript function myplugin_cast_vote, the onClick action for the button, which will read the information the user entered, compose a request with SACK, and send it to the plugin for processing. As mentioned in the introductory section, this JavaScript function and the SACK library need to get added to the HTML head section of the web page the user is viewing. One way to do that is to add it to all viewer-facing screens using the wp_head action (you could also be a little more selective by using some of the is_xyz() Conditional Tags tests). Let’s drop this in a plugin file myplugin.php:

add_action(‘wp_head’, ‘myplugin_js_header’ );

function myplugin_js_header() // this is a PHP function
{
// use JavaScript SACK library for Ajax
wp_print_scripts( array( ‘sack’ ));

// Define custom JavaScript function
?>

//

<?php
} // end of PHP function myplugin_js_header

Next activate the plugin and reload the HTML where the form is. By looking at the HTML source you should see the SACK Javascript library being loaded:

The next step is to fill in the body of the myplugin_cast_vote JavaScript function, which is supposed to read the vote from the form field, compose an Ajax request with SACK, and send the request to the server. Given the list of generic SACK information from the introductory section, here is what we need to set up for this example:

* Request URL: We need to send our request to a plugin PHP file. This should be the main plugin PHP file. In case you want it to be a separate PHP file, bare in mind that you won’t be able to access the WordPress global variables, e.g. $wpdb, since separate files have absolutely no visibility to any part of WordPress at all.
* Custom request variables: We need to send the vote and the ID of the div where the results go to the server, and also the function that will be called to process the vote in this simple example.

Putting this together, the body of the JavaScript function becomes:

function myplugin_cast_vote( vote_field, results_div )
{
var mysack = new sack(
“/wp-admin/admin-ajax.php” );

mysack.execute = 1;
mysack.method = ‘POST’;
mysack.setVar( “action”, “my_special_action” );
mysack.setVar( “vote”, vote_field.value );
mysack.setVar( “results_div_id”, results_div );
mysack.onError = function() { alert(‘Ajax error in voting’ )};
mysack.runAJAX();

return true;

} // end of JavaScript function myplugin_cast_vote

add_action(‘wp_ajax_my_special_action’, ‘my_action_callback’);
add_action(‘wp_ajax_nopriv_my_special_action’, ‘my_action_callback’);

Take special note of the Javascript code which has an “action” variable. Also take note that it is calling the admin-ajax.php file. Then note that my_special_action is part of the first parameter in the add_action call (wp_ajax_my_special_action). These are all significant.

The final step in this example is to define my_action_callback, which is what gets called when the Ajax request gets to the server. This will need to read the posted information, verify that the vote is valid, add the vote to the database, figure out what the new running totals are, and send that back to the browser. Leaving aside all the details of processing the vote, here’s what needs to go into the file:

That’s it! You will need to add a few details, such as error checking, escaping quotes, processing the vote, and verifying that the request came from the right place, but hopefully the example above will be enough to get you started on your own viewer-side Ajax plugin.

  1. Hello

    You will not believe what I just found! Foolioo.com makes free custom website for free. Yep! That’s right, FREE!
    Never thought it’d be so easy to get a free website and I really had to tell you guys.

    So if you’re looking for a free website, give these guys a try.

    Bye

  2. Thats an exact copy of what I found on codex. And its as useless as codex!

  3. These are basically brief phrase loans that do supply you meet your fiscal
    concerns within a preferred distinct time period. Thinking of time limitations these
    loans are specifically made above an obligation no cost platform.
    As such, these are kept completely no cost from credential checksums.
    Problems such as defaults, arrears, bankruptcy, CCJs and even IVAs are not viewed as right here.
    Further, there are also no collaterals connected with these loans.
    There is minimal paper perform required on the component
    of borrower. There are also no hidden or added documentation or faxing needed
    here. Applying for these loans is also extremely practical.
    Many people merely need filling an on the net type and as soon as this gets authorized cash is received inside
    24 hours time frame. These loans are frequently offered beneath convenient terms and circumstances.
    The common fundamental applicant criteria here is that they should be
    a UK resident and of 18 years of age.

  4. My brother suggested I might like this web site. He was entirely right.

    This post actually made my day. You cann’t imagine simply how much time I had spent for this info! Thanks! by Elizabeth see my site Fidel

  5. In short, they become obsessed by the grass is always greener syndrome where everyone else’s relationship and their own past lovers are elevated to the status of perfection. As Atlantis emerged from the blackness of space and into the blistering lights of the John F. Official Picture of President Reagan by the Executive Office of the Presidency used under Public Domain. I don’t want an strange voice to order me around.
    I’m hoping that all of you smarter ‘ more learned authors out there have a way to describe the intensity of this desire
    that you must have to journey in your own recovery.
    Originally established as a sanctuary for the
    Nilgiri Tahr, the ‘The Eravikulam National Park’
    has now turned into a highly popular tourist spot. We actually become happier people.
    Nevertheless, we’re now moving on and talking about the top Xbox 360 games for 2012. Do you want a top notch gaming PC that can play all the latest games at max or near max settings. When you set out to influence another’s feelings for you, are you not interfering with that person’s free will.

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: