WordPress.org

Ready to get started?Download WordPress

Codex

Function Reference/wp send json

Contents

Description

Send a JSON response back to an AJAX request, and die().

Usage

<?php wp_send_json( $response ) ?>

Parameters

$response
(mixed) (required) Variable (usually an array or object) to encode as JSON, then print and die.
Default: None

Examples

jQuery(document).ready(function(){

    jQuery('#btn_save').click(function(e){
       e.preventDefault();
                jQuery.post(pluginUrl+'ajax/save_field.php',jQuery('#my-form').serialize(), function(data) {                        
                alert(data.message + " ID:" + data.ID);
                //This will alert "Saved ID:1"
            });
    });

});

save_field.php

<?php
//bootstrap WP

$nonce=$_POST['_wpnonce_name'];
if (empty($_POST) || !wp_verify_nonce($nonce, 'my-nonce') ) die('Security check');

$return = array(
			'message'	=> 'Saved',
			'ID'		=> 1
	);

wp_send_json($return);

Default Usage

Change Log

Source File

wp_send_json() is located in wp-includes/functions.php

Related

wp_send_json_success(), wp_send_json_error()