Why use wp_send_json() over echo json_encode()?

The question:

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() over echo json_encode()?

Ref: wp_send_json

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

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.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment