It’s totally fine to manually call wp_die()
which works fine both with AJAX and non-AJAX requests. Just make sure you return a valid response body; e.g. if your JS expects a JSON response, then return a JSON-encoded string.
However, wp_send_json_error()
is a wrapper for wp_send_json()
which uses wp_die()
, so you don’t need to call wp_die()
if you’re using wp_send_json_error()
or wp_send_json_success()
.
Working Example
Client-side: Make AJAX request for an action named foo
. Let’s assume ajax_vars
is defined via wp_localize_script()
.
jQuery.ajax({
url: ajax_vars.ajax_url, // e.g. https://example.com/wp-admin/admin-ajax.php
data: { action: 'foo', nonce: ajax_vars.foo_nonce },
dataType: 'json', // <- we're expecting a JSON response
success ( res ) {
// Request succeeded, but we've got an error from the server - e.g. Due to
// an expired nonce.
if ( ! res.success ) {
console.log( res.data );
// Request succeeded; no errors thrown on the server.
} else {
console.log( res );
}
},
// Request failed - e.g. Due to an internal server error (parse/syntax error,
// etc.).
error ( xhr, error, status ) {
console.log( error, status );
}
});
Server-side: This function handles the above AJAX request.
function ajax_foo_handler() {
if ( ! check_ajax_referer( 'foo', 'nonce', false ) ) {
wp_send_json_error( 'Invalid Request' );
}
// Run your stuff...
wp_send_json_success( 'You may pass an array...' );
}
add_action( 'wp_ajax_foo', 'ajax_foo_handler' ); // for authenticated users
add_action( 'wp_ajax_nopriv_foo', 'ajax_foo_handler' ); // for non-authenticated users