I'm developing a plugin with an ajax handler. I first coded the ajax request setting up the XHR object. Looks like this:
var data = new FormData();
data.append('post_title', 'Hola como');
data.append('action', 'make_appointment');
var xhr = new XMLHttpRequest();
xhr.addEventListener('readystatechange', function() {
if (this.readyState === 4) {
console.log(this.responseText);
}
});
xhr.open('POST', 'http://wpapi.localdev/wp-admin/admin-ajax.php');
xhr.setRequestHeader('Cache-Control', 'no-cache');
xhr.send(data);
As you can notice I'm passing the action as part of the form data. This works fine but I wanted to use the fetch API instead because why not.
So I converted that to this:
let form = new FormData();
form.append('action', 'make_appointment');
form.append('post_title', 'hola como estas');
fetch(ajaxSettings.ajaxurl, {
method: 'POST',
headers: {
'Content-Type': 'multipart/form-data',
'Cache-Control': 'no-cache'
},
body: form
})
.then(response => {
console.log(response);
return response.text();
})
.then(response => {
console.log(response);
});
And this is not working, it just throws an 400 bad request error. I know that for some reason, the action parameter is not being sent correctly. Though, it works if, instead of sending the action as form data, I send it as a url parameter like this:
fetch(ajaxSettings.ajaxurl, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Cache-Control': 'no-cache'
},
body: '?action=make_appointment'
})
What am I doing wrong here? I just want to make it work as the XHR request, i.e. sending the action as form data. Notice that the ajax handler on the WordPress side already exists and works correctly.