do_action( "wp_ajax_{$action}" )

Fires authenticated Ajax actions for logged-in users.


Description Description

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


Top ↑

More Information 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

Top ↑

Source Source

File: wp-admin/admin-ajax.php

View on Trac


Top ↑

Changelog Changelog

Changelog
Version Description
2.1.0 Introduced.

Top ↑

User Contributed Notes User Contributed Notes

  1. Skip to note 1 content
    Contributed by stevenlinx

    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'].

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