1

I am trying to add users' emails to my Mailchimp 3.0 audience list. I am using JQuery to make the GET request, but I keep the following error:

{"type":"http://developer.mailchimp.com/documentation/mailchimp/guides/error-glossary/","title":"API Key Invalid","status":401,"detail":"Your request did not include an API key.","instance":"1e63d45d-2f46-481f-a674-3c307033cd29"}

This error happens after I click my button to trigger the request.

Here is the section in my HTML code that the JQuery script is pulling from:

<form **action="https://us4.api.mailchimp.com/3.0/lists/8a99d9c7eb/members/>"**
                                method="get" **id="mc-embedded-subscribe-form"** name="mc-embedded-subscribe-form" class="validate">
                                    <p class="signUp mt-5">
                                        We are currently Beta testing our service and will reveal more
                                        soon. Enter your email address below to receive updates.
                                    </p>
                                    <div class="form-label-group">
                                        <input type="email" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="form-control"
                                            placeholder="Email address" required autofocus>
                                    </div>

                                <input type="submit" value="Notify me" name="subscribe" id="mc-embedded-subscribe" class="btn btn-sm btn-success mt-1 shadow-lg">
                                <div id="subscribe-result"></div>
                                    <!-- <button class="btn btn-sm btn-success mt-1 shadow-lg" id="submitInfo"
                                        type="submit">Notify
                                        Me</button> -->
                                </form>

Here is my JQuery Code:

$(document).ready(function () {
 var $form = $('#mc-embedded-subscribe-form')
 if ($form.length > 0) {
   $('form input[type="submit"]').bind('click', function (event) {
     if (event) event.preventDefault()
     register($form)
   })
 }
})

function register($form) {
 $('#mc-embedded-subscribe').val('Sending...');
 $.ajax({
   type: $form.attr('method'),
   url: $form.attr('action'),
   data: $form.serialize(),
   status: "unsubscribed",
   headers: {
     'Authorization': 'Basic ' + new Buffer(`anything': 'apikey xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx-usx`)
   },
   cache: false,
   dataType: 'json',
   contentType: 'application/json; charset=utf-8',
   error: function (err) {
     alert('Could not connect to the registration server. Please try again later.')
   },
   success: function (data) {
     $('#mc-embedded-subscribe').val('subscribe')
     if (data.result === 'success') {
       // Yeahhhh Success
       console.log(data.msg)
       $('#mce-EMAIL').css('borderColor', '#ffffff')
       $('#subscribe-result').css('color', 'rgb(53, 114, 210)')
       $('#subscribe-result').html('<p>Thank you for subscribing. We have sent you a confirmation email.</p>')
       $('#mce-EMAIL').val('')
     } else {
       // Something went wrong, do something to notify the user.
       console.log(data.msg)
       $('#mce-EMAIL').css('borderColor', '#ff8282')
       $('#subscribe-result').css('color', '#ff8282')
       $('#subscribe-result').html('<p>' + data.msg.substring(4) + '</p>')
     }
   }
 })
};

I have tried to make this request using Fetch and AJAX, but no cigar. This approach has helped me make progress but ran into this little issue. I have reviewed the following questions and answers for additional support:

Javascript + MailChimp API subscribe

AJAX Mailchimp signup form integration Access MailChimp API 3.0 (GET)

Lastly, here is the MailChimp API documentation.

Add a Contact to a List/Audience (1 paragraph)

Add a new list member (search on "Add a new list member")

HTTP Basic Authentication(fourth paragraph)

Thank you for the help!!

1 Answers1

0

Exposing your API key on front-end is not a good idea. You can follow this approach to add users to specific List/ Audience

<!-- Please copy your form from Mailchimp Signup form ( condensed in your case ) or copy the form and input values from the form  -->
    <form action="Your url from signup form" method="get" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>
        <div id="mc_embed_signup_scroll">
        <label for="mce-EMAIL">Subscribe</label>
        <input type="email" value="" name="EMAIL" class="email" id="mce-EMAIL" placeholder="email address" required>
        <!-- real people should not fill this in and expect good things - do not remove this or risk form bot signups-->
        <div style="position: absolute; left: -5000px;" aria-hidden="true"><input type="text" name="from signup form" tabindex="-1" value=""></div>
        <div class="clear"><input type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="button"></div>
        </div>
    </form>

Below is the ajax request

$(document).ready(function () {
    $("#mc-embedded-subscribe-form").submit(function (e) {
        let form = $("#mc-embedded-subscribe-form")
        e.preventDefault();
        var settings = {
            url: form.attr('action'),
            type: form.attr('method'),
            data: form.serialize(),
            dataType: 'jsonp',
            contentType: "application/json; charset=utf-8",
        };
        $.ajax(settings).done(function (response) {
            console.log(response);
        });
    })
})
Akbar Ali
  • 446
  • 2
  • 7
  • This approach will open up a second form, designed by Mailchimp. I was hoping to keep my custom form with direct submission to my audience list. – Mark Dusseau Dec 29 '19 at 22:50
  • no it will submit the form without redirecting or anything. I tested this code and its works perfectly fine without any redirection or anything. You can design this form in your own way. – Akbar Ali Dec 29 '19 at 22:54
  • If you still want to keep the same form that you already have. just copy the form action url from Mailchip signup form and use the given jquery code – Akbar Ali Dec 29 '19 at 22:55
  • Ah I see. Thank you Akbar! – Mark Dusseau Dec 29 '19 at 23:02