wp_send_json_error( mixed $data = null, int $status_code = null, int $options )

Sends a JSON response back to an Ajax request, indicating failure.

Description

If the $data parameter is a WP_Error object, the errors within the object are processed and output as an array of error codes and corresponding messages. All other types are output without further processing.

Parameters

$datamixedoptional
Data to encode as JSON, then print and die.

Default:null

$status_codeintoptional
The HTTP status code to output.

Default:null

$optionsintoptional
Options to be passed to json_encode(). Default 0.

More Information

The response object will always have a success key with the value false. If anything is passed to the function in the $data parameter, it will be encoded as the value for a data key.

Source

function wp_send_json_error( $data = null, $status_code = null, $options = 0 ) {
	$response = array( 'success' => false );

	if ( isset( $data ) ) {
		if ( is_wp_error( $data ) ) {
			$result = array();
			foreach ( $data->errors as $code => $messages ) {
				foreach ( $messages as $message ) {
					$result[] = array(
						'code'    => $code,
						'message' => $message,
					);
				}
			}

			$response['data'] = $result;
		} else {
			$response['data'] = $data;
		}
	}

	wp_send_json( $response, $status_code, $options );
}

Changelog

VersionDescription
5.6.0The $options parameter was added.
4.7.0The $status_code parameter was added.
4.1.0The $data parameter is now processed if a WP_Error object is passed in.
3.5.0Introduced.

User Contributed Notes

  1. Skip to note 6 content

    Example

    jQuery( document ).ready( function() {
    
    	jQuery( '#btn_save' ).on( 'click', function( event ) {
    		event.preventDefault();
    		jQuery.post( pluginUrl + 'ajax/save_field.php', jQuery( '#my-form' ).serialize(), function( data ) {						
    			alert( data.success );
    		} );
    	} );
    } );

    save_field.php

    <?php
    $nonce = $_POST['_wpnonce_name'];
    if ( empty( $_POST ) || ! wp_verify_nonce( $nonce, 'my-nonce' ) ) {
    	wp_send_json_error(); // sends json_encoded success=false
    }

You must log in before being able to contribute a note or feedback.