WordPress.org

Codex

Attention Interested in functions, hooks, classes, or methods? Check out the new WordPress Code Reference!

Plugin API/Action Reference/wp ajax (action)

Description

This hook allows you to create custom handlers for your own custom AJAX requests. The wp_ajax_ hook follows the format "wp_ajax_$youraction", where $youraction is your AJAX request's 'action' property.

Usage

If you needed to create an AJAX handler for an "add_foobar" request, you would create a hook like this:

add_action( 'wp_ajax_add_foobar', 'prefix_ajax_add_foobar' );

function prefix_ajax_add_foobar() {
    // Handle request then generate response using WP_Ajax_Response

    // Don't forget to stop execution afterward.
    wp_die();
}

Using the above example, any time an AJAX request is sent to WordPress, and the request's 'action' property is set to 'add_foobar', this hook will be automatically executed. For example, the following code would execute the above hook.

jQuery.post(
    ajaxurl, 
    {
        'action': 'add_foobar',
        'data':   'foobarid'
    }, 
    function(response){
        alert('The server responded: ' + response);
    }
);

Note: The data (foobarid) would be available in your hook function from the $_POST array.

Example

This allows you to hook ajax requests.

ATTENTION: When you are writing a plugin (in plugin wp_ajax usage) place lines below in your main plugin file, e.g. myplugin.php

add_action( 'wp_ajax_my_ajax', 'my_ajax' );

function my_ajax() {
	die( "Hello World" );
}

Notes

  • The wp_ajax_ hook only fires for logged-in users. If you need to also listen for Ajax requests that don't come from logged-in users, you need to use wp_ajax_nopriv_, like this: add_action( 'wp_ajax_nopriv_add_foobar', 'prefix_ajax_add_foobar' );.

Related