0

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

  • As asked by Sally, can you help edit the code to include the alert("Hello") statement? Also response.data.messages should be used to get the desired data. – Vasanth Gopal Sep 9 at 4:26
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'
| improve this answer | |
  • Tried that @Sally CJ, but it's not getting past the success: function (response). I stuck an alert("Hello") on the next line and nothing. Not sure what this is but the Response Payload: 1 2 string(0) "" 3 {"success":true,"data":{"messages":"Enter a valid email"}}; – breadwild Sep 9 at 2:40
  • Try adding dataType: 'json' to the $j.ajax() args. But where is alert() in your code? – Sally CJ Sep 9 at 3:29
  • 1
    Insert embarrassment emoji. There was a stray var_dump in the PHP, hence the string(0). Through the old trick of commenting out halves of code, I found it. I used to see this in my old Perl debugging. Anyway, now works as advertised. dataType is not needed, the response header clearly shows json Sorry for the trouble. – breadwild Sep 9 at 13:12

Not the answer you're looking for? Browse other questions tagged or ask your own question.