do_action( “wp_ajax_{$action}” )

Fires authenticated Ajax actions for logged-in users.

Description

The dynamic portion of the hook name, $action, refers to the name of the Ajax action callback being fired.

More Information

  • This hook allows you to handle your custom AJAX endpoints. The wp_ajax_ hooks follows the format “wp_ajax_$action“, where $action is the ‘action‘ field submitted to admin-ajax.php.
  • This hook only fires for logged-in users. If your action only allows Ajax requests to come from users not logged-in, you need to instead use wp_ajax_nopriv_$action such as: add_action( 'wp_ajax_nopriv_add_foobar', 'prefix_ajax_add_foobar' );. To allow both, you must register both hooks!
  • See also wp_ajax__requestaction
  • See also Ajax Plugin Handbook

Source

do_action( "wp_ajax_{$action}" );

Changelog

VersionDescription
2.1.0Introduced.

User Contributed Notes

  1. Skip to note 3 content

    Example migrated from Codex:

    If you need to create an AJAX handler for an “add_foobar” request, you would create a hook like this:

    add_action( 'wp_ajax_foobar', 'my_ajax_foobar_handler' );
    
    function my_ajax_foobar_handler() {
        // Make your response and echo it.
    
        // Don't forget to stop execution afterward.
        wp_die();
    }

    The following code is an example using jQuery that would trigger the above hook.

    jQuery.post(
        my_foobar_client.ajaxurl, 
        {
            'action': 'foobar',
            'foobar_id':   123
        }, 
        function(response) {
            console.log('The server responded: ', response);
        }
    );

    Note: The foobar_id would be available in your PHP hook handler via $_POST['foobar_id'].

  2. Skip to note 4 content

    using wp_send_json() to output your result as a json format

    add_action( 'wp_ajax_foobar_json', 'my_ajax_foobar_json_handler' );
    function my_ajax_foobar_json_handler() {
        // Your response in array
    	$array_result = array(
    		'data' => 'your data',
    		'message' => 'your message'
    	);
    
        // Make your array as json
    	wp_send_json($array_result);
     
        // Don't forget to stop execution afterward.
        wp_die();
    }

You must log in before being able to contribute a note or feedback.