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!
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.
Example migrated from Codex:
If you need to create an AJAX handler for an “
add_foobar
” request, you would create a hook like this:The following code is an example using jQuery that would trigger the above hook.
Note: The
foobar_id
would be available in your PHP hook handler via$_POST['foobar_id']
.using wp_send_json() to output your result as a json format
wp_die()
when usingwp_send_json()
.wp_die()
is not needed here, sincewp_send_json()
already makes awp_die()