wp_send_json_success() WP 3.5.0
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).
Works based on: wp_send_json()
No Hooks.
Return
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().
Default: 0
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. |
Code of wp_send_json_success() wp send json success WP 5.6
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 );
}Related Functions
From tag: AJAX
More from category: Helper Functions
- __return_empty_array()
- __return_empty_string()
- __return_false()
- __return_null()
- __return_true()
- __return_zero()
- build_query()
- get_page_hierarchy()
- get_temp_dir()
- human_readable_duration()
- is_email()
- is_php_version_compatible()
- is_serialized()
- is_serialized_string()
- is_wp_version_compatible()
- map_deep()
- maybe_serialize()
- maybe_unserialize()
- path_join()
- seems_utf8()
- stripslashes_deep()
- timer_stop()
- urlencode_deep()
- wp_array_slice_assoc()
- wp_basename()
- wp_debug_backtrace_summary()
- wp_extract_urls()
- wp_filter_object_list()
- wp_generate_uuid4()
- wp_html_split()
- wp_is_json_request()
- wp_is_numeric_array()
- wp_is_uuid()
- wp_kses_array_lc()
- wp_kses_hair()
- wp_kses_uri_attributes()
- wp_list_filter()
- wp_list_pluck()