wordpress ajax rest api ("code":"rest_invalid_json","message":"Invalid JSON body passed.")

I dont understand what i did wrong, can anyone give me a suggestion on what causes the above error below is my code. I can confirm that, i am hitting the route, succesfully because the code inside get it executed. I am also adding the 1 value at the end, to be passed it to json as per wp_send_json_success. At this point i dont know what to next, can anyone explaint to me, on what is going on?

route.php

function update_employee_photo($request){
    global $wpdb;
    $data_with_photo = array(
            'photo'             => $request['photo'],
            'photo_privacy'     => $request['photoPrivacy'],
            'photo_description' => $request['photoDescription']
    );
    $data_null_photo = array(
        'photo_privacy'     => $request['photoPrivacy'],
        'photo_description' => $request['photoDescription']
    );

    $data   = ($request['photo'] != "null") ? $data_with_photo : $data_null_photo;
    $where  = array('wp_user_id' => get_current_user_id());
    $result = $wpdb->update("aupair_registered_employee", $data, $where);
    if($result){
        wp_send_json_success($result, 200, 1);
    } else {
        wp_send_json_error($wpdb->last_query);
    }
    die();
}

add_action('rest_api_init', function(){
    register_rest_route( 'activeAupair/v1', '/updateEmployeePhoto', [
        'methods'  => 'POST',
        'callback' => 'update_employee_photo'
    ]);
});

file.js

  $.ajax({
            type: 'POST',
            url: myAjax.restURL + 'activeAupair/v1/updateEmployeePhoto',
            contentType: 'application/json',
            datatype: 'json',
            data: {
                photo: photo,
                photoPrivacy: getPhotoPrivacy(),
                photoDescription: getPhotoDescription()
            },
            beforeSend: function (xhr) {
                xhr.setRequestHeader('X-WP-Nonce', myAjax.nonce);
            },
            success: function(response){
                console.log('TYPE OF ', typeof response);
                console.log('RESPONSE ', response);
                msg.empty();
                msg.append($('<p id="required"></p>').text('Updated'));
                uploadBtn.attr('value', 'Update');
                uploadBtn.attr('disabled', false);
            },
            error: function (xhr, ajaxOptions, thrownError) {
            },
            complete: function(data){
               console.log('COMPLETE ', data);
            }
      });

console error

1 answer

  • answered 2021-06-19 18:08 Pirate of KGP

    As per the wordpress wp_send_json_success() function expect third parameter 1(default 0) to encode it into JSON format (see the refference). So you need to pass the status code as second parameter and 1 for the JSON object.

    wp_send_json_success($result, 200, 1);