Unable to parse JSON response from wp_send_json_success

Trying to do this the WordPress way: wp_send_json_success

PHP processing save_form return:

        $response = array( 'messages' => $message );
        wp_send_json_success( $response );

jQuery:

        $j.ajax({
            type: 'POST',
            url: ajax_url,
            data: {
                    action:         'save_form',
                    form_id:        $j('#form_id').val(),
                    full_name:      $j('#full_name').val(),
                    email:          $j('#email').val(),
                    signup_nonce:   $j('#signup_nonce').val()
                },
            success: function (response) {
                    console.log(response.messages);
                },
            error: function (response) { }
        });
        return false;

Response in the Inspector:

JSON:
success: true
data: Object { messages: "Enter a valid email address" }
    messages: "Enter a valid email address"

but…

console.log(response.messages);

returns nothing.

What am I missing?

Thanks, Brad

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

In short, you should use response.data.messages.

And that’s because wp_send_json_success() will send a JSON response (an object) with the property data set to whatever that you passed to the function.

wp_send_json_success( 123 );
// In JS, response.data would be an integer. I.e. response.data = 123

wp_send_json_success( array( 'foo' => 'bar' ) );
// In JS, response.data would be an object. So response.data.foo = 'bar'


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x