Submit Embedded Mailchimp Form with Javascript AJAX (not jQuery) Submit Embedded Mailchimp Form with Javascript AJAX (not jQuery) ajax ajax

Submit Embedded Mailchimp Form with Javascript AJAX (not jQuery)


A few days back I've had the exact same problem and as it turns out the MailChimp documentation on native JavaScript is pretty sparse. I can share with you my code I came up with. Hope you can build from here!

The simplified HTML form: I've got the from action from the MailChimp form builder and added "post-json"

<div id="newsletter">    <form action="NAME.us1.list-manage.com/subscribe/post-json?u=XXXXXX&id=XXXXXXX">        <input class="email" type="email" value="Enter your email" required />        <input class="submit" type="submit" value="Subscribe" />    </form></div>

The JavaScript: The only way to avoid the cross-origin problem is to create a script and append it to the header. The callback occurs then on the ā€œcā€ parameter. (Please note there is no email address validation on it yet)

function newsletterSubmitted(event) {    event.preventDefault();    this._form = this.querySelector("form");    this._action = this._form.getAttribute("action");    this._input = this._form.querySelector("input.email").value;    document.MC_callback = function(response) {        if(response.result == "success") {            // show success meassage        } else {            // show error message        }    }    // generate script    this._script = document.createElement("script");    this._script.type = "text/javascript";    this._script.src = this._action + "&c=document.MC_callback&EMAIL=" + this._input;    // append script to head        document.getElementsByTagName("head")[0].appendChild(this._script);}var newsletter = document.querySelector("#newsletter")newsletter.addEventListener("submit", newsletterSubmitted);