wp_send_json

Send a JSON response back to an Ajax request.

Description

wp_send_json( (mixed) $response, (null) $status_code = null ); 

Parameters (2)

0. $response (mixed)
Variable (usually an array or object) to encode as JSON, then print and die.
1. $status_code — Optional. (null) => null
The HTTP status code to output.

Usage

  1. if ( !function_exists( 'wp_send_json' ) ) { 
  2. require_once ABSPATH . WPINC . '/functions.php'; 
  3.  
  4. // Variable (usually an array or object) to encode as JSON, 
  5. // then print and die. 
  6. $response = null; 
  7.  
  8. // The HTTP status code to output. 
  9. $status_code = null; 
  10.  
  11. // NOTICE! Understand what this does before running. 
  12. $result = wp_send_json($response, $status_code); 
  13.  

Defined (1)

The function is defined in the following location(s).

/wp-includes/functions.php  
  1. function wp_send_json( $response, $status_code = null ) { 
  2. @header( 'Content-Type: application/json; charset=' . get_option( 'blog_charset' ) ); 
  3. if ( null !== $status_code ) { 
  4. status_header( $status_code ); 
  5. echo wp_json_encode( $response ); 
  6.  
  7. if ( wp_doing_ajax() ) { 
  8. wp_die( '', '', array( 
  9. 'response' => null,  
  10. ) ); 
  11. } else { 
  12. die;