I'm trying to convert an .ajax call to a fetch call. The ajax works but the fetch pulls a 500 error when I try to pull the data in my wordPress php file.
I'm fairly new to the fetch api and that is why I'm trying to learn it. I have looked at MDN, wordPress site on custom hooks and rest api, searched the web and searched stack overflow. All they talk about is ajax. I don't know if I'm using the wrong search phrase but I have been trying to figure this out for hours and frustrated.
//working ajax in js file
createLike() {
$.ajax({
url: `${universityData.root_url}/wp-json/university/v1/manageLike`,
type: 'POST',
data: {'professorId' : 789},
success: response => {
console.log(response);
},
error: response => {
console.log(response);
}
});
//my conversion to fetch
createLike() {
const data = {
'professorId' : 789,
};
fetch(`${universityData.root_url}/wp-json/university/v1/manageLike`, {
headers: {
'X-WP-Nonce' : universityData.nonce,
'Content-Type' : 'application/json'
},
credentials: 'same-origin',
method: 'POST',
body: JSON.stringify(data),
}).then(function(response){
return response.json();
}).then(response => {
console.log(response);
}).catch(err => console.log(`error : ${err}`))
},
//php file
function createLike($data) {
$professor = sanatize_text_field($data['professorId']);
wp_insert_post(array(
'post_type' => 'like',
'post_status' => 'publish',
'post_title' => '3rd PHP Create Post Test',
'meta_input' => array(
'liked_professor_id' => $professor
)
));
}
function universityLikeRoutes() {
register_rest_route('university/v1', 'manageLike', array(
'methods' => 'POST',
'callback' => 'createLike',
));
}
add_action('rest_api_init', 'universityLikeRoutes');
my error
{code: "internal_server_error", message: "The site is experiencing technical difficulties.", data: {…}, additional_errors: Array(0)}
additional_errors: []
code: "internal_server_error"
data: {status: 500}
message: "The site is experiencing technical difficulties."
__proto__: Object
The key is understanding what $.ajax()
does differently than fetch
and thus how you have to handle the data differently in wordpress.
$.ajax
takes whatever you pass to the data
option and converts into the application/x-www-form-urlencoded
MIME type by default. $_POST
in PHP automatically decodes indexed form variable names, which the WP_REST_Request
object makes available to you within your callback as the $data
argument.
fetch
is different in several ways, you can read about this in several articles online, such as this one. One thing you are doing differently is passing along a serialized JSON string and you are telling your endpoint that the data type is application/json
. By design, the wp-json
API doesn't by default parse this data for you. But you can access it nevertheless.
Instead of using $data
as your callback argument, change it to a WP_REST_Request
object. Then you can call the get_json_params
method, and access whatever body you passed to the api that way.
For instance, change your PHP
callback to the following:
function createLike( WP_REST_Request $request ) {
$data = $request->get_json_params();
$professor = sanitize_text_field( $data['professorId'] );
wp_insert_post( array(
'post_type' => 'like',
'post_status' => 'publish',
'post_title' => '3rd PHP Create Post Test',
'meta_input' => array(
'liked_professor_id' => $professor
)
) );
}