Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Submit Embedded Mailchimp Form with Javascript AJAX (not jQuery)

I have been trying to submit an embedded Mailchimp form with AJAX but without using jQuery. Clearly, I am not doing this properly, as I keep ending up on the "Come, Watson, come! The game is afoot." page :(

Any help with this would be greatly appreciate.

The form action has been altered to replace post?u= with post-json?u= and &c=? has been added to the end of the action string. Here is my js:

document.addEventListener('DOMContentLoaded', function() {

    function formMailchimp() {

        var elForm         = document.getElementById('mc-embedded-subscribe-form'),
            elInputName    = document.getElementById('mce-NAME'),
            elInputEmail   = document.getElementById('mce-EMAIL'),
            strFormAction  = elForm.getAttribute('action');

        elForm.addEventListener('submit', function(e) {

            var request = new XMLHttpRequest();

            request.open('GET', strFormAction, true);
            request.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');

            request.onload = function() {

                if (request.status >= 200 && request.status < 400) {

                    // Success!
                    var resp = JSON.parse(request.responseText);

                    request.send(resp);

                } else {

                    console.log('We reached our target server, but it returned an error');

                }

            };

            request.onerror = function() {
                console.log('There was a connection error of some sort');
            };

        });

    }

    formMailchimp();

});

Also, I anticipate the inevitable "why don't you just use jQuery" comment. Without going into the specifics of this project, jQuery is not something I am able to introduce into the code. Sorry, but this HAS to be vanilla javascript. Compatibility is for very modern browsers only.

Thanks so much for any help you can provide!

like image 358
beefchimi Avatar asked Mar 06 '15 21:03

beefchimi


1 Answers

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&amp;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);
like image 162
Hanslibuzli Avatar answered Sep 29 '22 20:09

Hanslibuzli