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
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
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