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