When sending a JSON response back to an AJAX request, why use the WordPress function
wp_send_json() and not
echo json_encode()? What is the benefit of using the WordPress function
wp_send_json() handles all parts of returning content in an AJAX call. First off, it sets the content type of the returned content to
application/json with the proper charset. Secondly, it automatically calls
wp_die() after sending the JSON result, which is necessary in an AJAX call in WordPress.
You could consider using
wp_send_json_success() for successful requests and
wp_send_json_error() for erroneous requests, thereby adhering to the WordPress standards for handling AJAX requests. These functions set a
success (boolean) and
data (any type) key in an array and encode that entire array, thereby allowing you easily check in a structured way whether the request was successful or whether something went wrong.