I am making some progress with creating a custom plugin, and am curious as to whether I am following proper "Craft standards". Here is my scenario:
A user needs to submit a one field form that contains their email address. Upon button click, I would like to prevent the default action, and send the email address via AJAX to my plugin for processing.
After reading through the Craft Plugin Docs, I am under the impression that my plugin requires the following functionality(and in this order).
- Send email address via AJAX to a Controller.
- The controller will then extract the email, and send it off to a Service.
- The Service, is where I should write my code that connects to the MailChimp API
- Send the result of whether the Mailchimp API request was successful from the Service, back to the Controller.
- The Controller will then send back the response to my JavaScript, where I will ultimately display a success or error message to the user.
I have been successful in sending an AJAX request from my JavaScript code to my Controller via the following code, and receiving some dumby test text.
function sendAjax() {
var xhr = new XMLHttpRequest()
xhr.open('POST', siteUrl + 'ajax/ajax-mailchimp.html')
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8')
xhr.onload = function() {
if(xhr.status === 200) {
console.log(xhr.responseText)
}
}
xhr.send(encodeURI('action=/craftMailchimped/submittal/receiveEmail&[email protected]'))
}
In my controller, I have the following:
<?php
namespace Craft;
class CraftMailchimped_SubmittalController extends BaseController {
public function actionReceiveEmail() {
echo 'Wuzup?';
}
}
In case you are wondering what 'ajax/ajax-mailchimp.html' is, its an empty template file, with no code in it. I did this, because I didn't really know what to put in as the URL in the xhr.POST method in my JavaScript code.
I am concerned I am not going about this in the right way, as I wouldn't even know how I would extract the email address inside my controller.
Any help on this?
My Form HTML for reference:
<form id="updates" class="mchimp">
<p class="newsletter">
{{ entry.connectNewsletterCta }}
</p>
<div class="elements-wrapper">
<input type="email" placeholder="Enter your email" required>
<button class="btn">
{{ entry.connectNewsletterButtonText }}
</button>
</div>
</form>