Creating Ajax Calls

 

AJAX handlers are easy to add. This involves two things: (1) a function to handle an AJAX call and (2) that method being registered to a URL.

See also: http://codex.wordpress.org/AJAX_in_Plugins

1. Create a function to handle an AJAX call

In your your XXX_Plugin.php class file, add a new function call like this:

1
2
3
4
5
6
7
8
9
10
11
public function ajaxACTION() {
    // Don't let IE cache this request
    header("Pragma: no-cache");
    header("Cache-Control: no-cache, must-revalidate");
    header("Expires: Thu, 01 Jan 1970 00:00:00 GMT");
 
    header("Content-type: text/plain");
 
    echo 'hello world';
    die();
}

Change “ACTION” in the function name to something meaningful to you.

The first three header lines ensure that browsers do not cache the results of the first call to this function via AJAX (after which it would simply return that cached results instead of actually making the call). IE tends to cache by default. This usually doesn’t make sense for AJAX calls.

Change the content type header to what you want (like “application/json” for JSON).

The “echo ‘Hello World'” line is where your content would go.

You need to end with the “die()” call in AJAX handler functions. This is related to how AJAX requests are handled by WordPress.

2. Register the function to an AJAX URL

In the same XXX_Plugin.php file, find the function addActionsAndFilters(). In that function register your AJAX function to a WP AJAX action name:

1
2
3
4
public function addActionsAndFilters() {
   add_action('wp_ajax_ACTION', array(&$this, 'ajaxACTION'));
   add_action('wp_ajax_nopriv_ACTION', array(&$this, 'ajaxACTION')); // optional
}

Where “ajaxACTION” is the name of your function. The “ACTION” part of “wp_ajax_ACTION” and “wp_ajax_nopriv_ACTION” is a unique name for your AJAX action.

  • Registering wp_ajax_ACTION makes the AJAX call accessible to users who are logged into your site and have privileges. This is for security. You always need to have this line.
  • Only add the wp_ajax_nopriv_ACTION line if you want the AJAX call to be accessible to non-logged-in users.
  • NOTE: if you added the wp_ajax_nopriv_ACTION one but not the wp_ajax_ACTION one, then the AJAX call would be available to non-logged-in users but NOT to logged in users.

3. The AJAX URL

OK, you created a function and registered it. But what is the URL to it? The URL can be composed via

1
admin_url('admin-ajax.php') . '?action=' . $actionName;

for which there is a convenience function

1
$this->getAjaxUrl($actionName);

You can add additional GET parameters to an AJAX call like this:

1
2
3
4
5
6
$plainUrl = $this->getAjaxUrl('MyAjaxActionName);
$urlWithId = $this->getAjaxUrl('MyAjaxActionName&id=MyId);
 
// More sophisticated:
$parametrizedUrl = $this->getAjaxUrl('MyAjaxActionName&id=%s&lat=%s&lng=%s);
$urlWithParamsSet = sprintf($parametrizedUrl, urlencode($myId), urlencode($myLat), urlencode($myLng));

 4. Role-Based Security in AJAX Calls

wp_ajax_ACTION and wp_ajax_nopriv_ACTION are a bit coarse-grained. A more nuanced security check can be done programmatically in the function:

1
2
3
4
5
6
7
public function ajaxACTION() {
    if (!$this->isUserRoleEqualOrBetterThan('Author')) {
        die(1);
   }
    // do operation
    die();
}

Here we check that the user has at least Author role.

But we can also use a “role option” so that the plugin administrator can choose the role needed for a certain operation.

1
2
3
4
5
6
7
public function ajaxACTION() {
    if (!$this->canUserDoRoleOption('CanDoXXXOperation')) {
        die(1);
    }
    // do operation
    die();
}

In this example, ‘CanDoXXXOperation’ is defined as a “Role Option”…a concept in this plugin template code. You can define an option (a.k.a setting) that will appear on your plugin’s option page. You can then set the level of user (Administrator, Editor, Author, Contributor, Subscriber, Anyone) that can access the method. See more about role options.

5. Error Handling

Options you have for reporting errors include:

  • Use the die(1) call to indicate an error for calls for data like JSON.
  • Silently do no operation in the function. Finish with die();
  • If you are returning a message that is displayed on the page, echo the message and call die()

 

  4 Responses to “Creating Ajax Calls”

  1. Thanks for this great tutorial. It just helped me using Ajax the correct way for the WP-Plugin that I’m developing at the moment.

  2. I could not understand how it works. Where do I write a form and where does the submit button and the onClick event of Ajax depend? I’ve really been trying for three days and I can not. The rest of the plugin I got, but AJAX does not. Could you post the complete code?

  3. My plugin activation process terminates with a fatal error when ‘public’ precedes the function definition.
    Would that be due to a local/environmental setting?

    Also, if I substituted “ABCDEF” (upper-case) for “ACTION” in the function name and the add_action, would that cause a problem? Or, should it be all lower-case? I keep receiving 400 errors, so there must be something wrong with my request details.

Leave a Reply to Clodoaldo Cancel reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>