wp_send_json_success()
Returns JSON data. Is used to return a success response to AJAX request. The response object always contains the element success=true
. die() php execution.
wp_send_json_error() is a similar function, but used to return errors response (not success).
Uses: wp_send_json()
No Hooks.
Return
null
. Nothing (null). Displays JSON data, and exit php.
Data passed to the $data parameter will be added to response:
// this is how returned data looks, before encoding to JSON: $response = array( 'success' => true ); // if $data not passed $response = array( 'success' => true, 'data' => $data ); // if $data passed
Usage
wp_send_json_success( $data, $status_code, $options );
- $data(mixed)
- Data to encode as JSON, then print and die.
Default: null - $status_code(int)
- The HTTP status code to output.
Default: null - $options(int)
- Options to be passed to json_encode().
Examples
#1 The definition of a successful AJAX request
This jQuery code sends an AJAX request to the ajax/save_field.php
plugin file:
jQuery(document).ready(function($){ $('#btn_save').click( function(e){ e.preventDefault(); $.post( pluginUrl + 'ajax/save_field.php', $('#my-form').serialize(), function( json ){ if( json.success ) alert( json.data.message ); else alert( 'Error' + json.data ); }); }); });
This is the code of the file save_field.php, which processes the transmitted request. Code below shows how wp_send_json_success() is used:
<?php // load WP environment $return = array( 'message' => 'Saved', 'ID' => 1 ); wp_send_json_success( $return );
Changelog
Since 3.5.0 | Introduced. |
Since 4.7.0 | The $status_code parameter was added. |
Since 5.6.0 | The $options parameter was added. |
wp_send_json_success() wp send json success code WP 6.4.1
function wp_send_json_success( $data = null, $status_code = null, $options = 0 ) { $response = array( 'success' => true ); if ( isset( $data ) ) { $response['data'] = $data; } wp_send_json( $response, $status_code, $options ); }