The issue in your code is simple: if you want to send a JSON response, then make sure it’s a valid JSON response, i.e. send the correct Content-Type
header and a proper JSON-encoded body. With jQuery.ajax()
, though, you can omit the header, but you’d need to set the dataType
to json
.
function my_ajax_callback1() {
// Invalid JSON response.
die();
}
function my_ajax_callback2() {
// Good JSON response with a Content-Type header.
header( 'Content-Type: application/json' );
echo json_encode( array( 'update' => true ) );
wp_die(); // die() works, but wp_die() is better
}
And actually, in your callback, you could simply use wp_send_json()
like so:
function my_ajax_callback3() {
wp_send_json( array( 'update' => true ) );
// No need to call wp_die(), die() or exit().
}
And there also wp_send_json_success()
and wp_send_json_error()
, but in your JS, you would need to use data.data.<key>
and not data.<key>
, except for data.success
.
function my_ajax_callback4() {
// ... your code
// In your success( data ) JS, you'd access the 'update' value via data.data.update
if ( $result ) {
wp_send_json_success( array( 'update' => true, 'msg' => 'Success!' ) );
} else {
wp_send_json_error( array( 'update' => false, 'msg' => 'Foo error' ) );
}
}
So be sure to return a valid response data and although not required, I suggest you to consider creating a custom REST API endpoint for your custom AJAX action and point your AJAX requests to that API endpoint — which (by default) always returns a JSON response.