From c8a328f100c95791e6770ef0c9840f0957cca381 Mon Sep 17 00:00:00 2001 From: Andrew Nacin Date: Fri, 31 Aug 2012 01:56:00 +0000 Subject: [PATCH] Introduce wp_send_json() to json-encode a variable, print it, and die, for Ajax requests. Effectively replaces WP_Ajax_Response, which was an XML-based response. Introduce wp_send_json_success() and wp_send_json_error(), which will allow us to fire appropriate done() or fail() callbacks in JS. props koopersmith. see #21390. git-svn-id: http://core.svn.wordpress.org/trunk@21679 1a063a9b-81f0-0310-95a4-ce76da25c4cd --- wp-includes/functions.php | 52 +++++++++++++++++++++++++++++++++++++-- 1 file changed, 50 insertions(+), 2 deletions(-) diff --git a/wp-includes/functions.php b/wp-includes/functions.php index b6e9b7e0fc..e369fff3a5 100644 --- a/wp-includes/functions.php +++ b/wp-includes/functions.php @@ -1799,7 +1799,7 @@ function wp_get_mime_types() { 'mid|midi' => 'audio/midi', 'wma' => 'audio/wma', 'mka' => 'audio/x-matroska', - // Misc application formats + // Misc application formats 'rtf' => 'application/rtf', 'js' => 'application/javascript', 'pdf' => 'application/pdf', @@ -1857,7 +1857,7 @@ function wp_get_mime_types() { * * @uses apply_filters() Calls 'upload_mimes' on returned array * @uses wp_get_upload_mime_types() to fetch the list of mime types - * + * * @return array Array of mime types keyed by the file extension regex corresponding to those types. */ function get_allowed_mime_types() { @@ -2142,6 +2142,54 @@ function _scalar_wp_die_handler( $message = '' ) { die(); } +/** + * Send a JSON response back to an Ajax request. + * + * @since 3.5.0 + * + * @param mixed $response Variable (usually an array or object) to encode as JSON, then print and die. + */ +function wp_send_json( $response ) { + @header( 'Content-Type: application/json; charset=' . get_option( 'blog_charset' ) ); + echo json_encode( $json ); + if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) + wp_die(); + else + die; +} + +/** + * Send a JSON response back to an Ajax request, indicating success. + * + * @since 3.5.0 + * + * @param mixed $data Data to encode as JSON, then print and die. + */ +function wp_send_json_success( $data = null ) { + $response = array( 'success' => true ); + + if ( isset( $data ) ) + $response['data'] = $data; + + wp_send_json( $response ); +} + +/** + * Send a JSON response back to an Ajax request, indicating failure. + * + * @since 3.5.0 + * + * @param mixed $data Data to encode as JSON, then print and die. + */ +function wp_send_json_error( $data = null ) { + $response = array( 'success' => false ); + + if ( isset( $data ) ) + $response['data'] = $data; + + wp_send_json( $response ); +} + /** * Retrieve the WordPress home page URL. *