WordPress at a glance

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 );
$data(mixed)
Data to encode as JSON, then print and die.
Default: null
$status_code(int)
The HTTP status code to output.
Default: null

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.

Code of wp send json success: wp-includes/functions.php WP 5.2.4

<?php
function wp_send_json_success( $data = null, $status_code = null ) {
	$response = array( 'success' => true );

	if ( isset( $data ) ) {
		$response['data'] = $data;
	}

	wp_send_json( $response, $status_code );
}

Related Functions

From tag: AJAX

More from category: Helper Functions

vladlu 100vlad.lu
Editors: kama 100
No comments
    Hello, !     Log In . Register