Make WordPress Core

Changeset 21679


Ignore:
Timestamp:
08/31/2012 01:56:00 AM (12 years ago)
Author:
nacin
Message:

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.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/wp-includes/functions.php

    r21664 r21679  
    18001800    'wma' => 'audio/wma',
    18011801    'mka' => 'audio/x-matroska',
    1802     // Misc application formats 
     1802    // Misc application formats
    18031803    'rtf' => 'application/rtf',
    18041804    'js' => 'application/javascript',
     
    18581858 * @uses apply_filters() Calls 'upload_mimes' on returned array
    18591859 * @uses wp_get_upload_mime_types() to fetch the list of mime types
    1860  * 
     1860 *
    18611861 * @return array Array of mime types keyed by the file extension regex corresponding to those types.
    18621862 */
     
    21412141        die( (string) $message );
    21422142    die();
     2143}
     2144
     2145/**
     2146 * Send a JSON response back to an Ajax request.
     2147 *
     2148 * @since 3.5.0
     2149 *
     2150 * @param mixed $response Variable (usually an array or object) to encode as JSON, then print and die.
     2151 */
     2152function wp_send_json( $response ) {
     2153    @header( 'Content-Type: application/json; charset=' . get_option( 'blog_charset' ) );
     2154    echo json_encode( $json );
     2155    if ( defined( 'DOING_AJAX' ) && DOING_AJAX )
     2156        wp_die();
     2157    else
     2158        die;
     2159}
     2160
     2161/**
     2162 * Send a JSON response back to an Ajax request, indicating success.
     2163 *
     2164 * @since 3.5.0
     2165 *
     2166 * @param mixed $data Data to encode as JSON, then print and die.
     2167 */
     2168function wp_send_json_success( $data = null ) {
     2169    $response = array( 'success' => true );
     2170
     2171    if ( isset( $data ) )
     2172        $response['data'] = $data;
     2173
     2174    wp_send_json( $response );
     2175}
     2176
     2177/**
     2178 * Send a JSON response back to an Ajax request, indicating failure.
     2179 *
     2180 * @since 3.5.0
     2181 *
     2182 * @param mixed $data Data to encode as JSON, then print and die.
     2183 */
     2184function wp_send_json_error( $data = null ) {
     2185    $response = array( 'success' => false );
     2186
     2187    if ( isset( $data ) )
     2188        $response['data'] = $data;
     2189
     2190    wp_send_json( $response );
    21432191}
    21442192
Note: See TracChangeset for help on using the changeset viewer.