wp_send_json_success

Home » Functions » wp_send_json_success

Function Name: wp_send_json_success

If you want to send a JSON response to an AJAX request, then wp_send_json_success() function is a great option. This function packs the data you want to send into a JSON object and sends it back, along with a ‘success’ flag to indicate that the request was successful.

This function is used to send an AJAX response containing a JSON success message with arbitrary data, and then terminates execution by calling wp_die(). By default, it returns a 200 response code, but you can change it if you need to.

Here’s an example usage code:

function my_ajax_function() {
  // perform some action here
  $data = array(
    'message' => 'Success!',
    'data'    => array(
      'name'    => 'John Doe',
      'email'   => 'johndoe@email.com',
      'phone'   => '555-555-5555'
    )
  );
  wp_send_json_success($data);
}
add_action('wp_ajax_my_ajax_function', 'my_ajax_function');

In this example, we define a function that performs some action and creates a data array. We then pass this array to wp_send_json_success() function, which sends back a JSON success message with the data array. This function can be used in any AJAX request where you need to send back JSON data.

Learn More on WordPress.org

Register an account to save your snippets or go Pro to get more features.