Codex

Plugin API/Action Reference/wp ajax (action)

Contents

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
 }

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.

add_action('wp_ajax_my_ajax', 'my_ajax');

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

Related