I want to use Ajax to POST to a plugin endpoint and get a JSON response. The plugin I'm using is for Mailchimp newsletter subscriptions and should allow for JSON responses:
https://github.com/aelvan/mailchimp-subscribe-craft
I have my form:
<form action="" method="post" novalidate>
{{ csrfInput() }}
<input id="email" name="email" type="email" >
<input type="submit" value="Subscribe">
and my Javascript:
let json = this.toJSONString(this.form);
let xhr = new XMLHttpRequest();
xhr.onload = () => {
if (xhr.status >= 200 && xhr.status < 300) {
// ...
} else {
// ...
}
};
xhr.open("POST", "actions/mailchimp-subscribe/audience/subscribe", true);
xhr.setRequestHeader("Content-Type", "application/json; charset=UTF-8");
xhr.send(json);
This hits the endpoint, but I get a 404 response:
HTTP 404 – Not Found – yii\web\NotFoundHttpException
Template not found: actions/mailchimp-subscribe/audience/subscribe
As I understand it, I'm correctly posting to the relevent plugin controller action by using the URL actions/mailchimp-subscribe/audience/subscribe
. Furthermore, if I do a GET to that URL I get a 400
response which would lead me to believe the routing is correct.
The error therefore seems to be in the Craft controller/routing handler. It's not detecting that I've send a JSON string and that I want a JSON response (and not a template/HTML response).
What's going on here?