9

There has been a big update on the Mailchimp API (v3.0) and many of the jQuery plugins are out of date in order to POST subscribers on form.submit().

After reading v3.0 docs:

Managing subscribers suggests the following JSON object format:

{
   "email_address": "urist.mcvankab@freddiesjokes.com", 
   "status": "subscribed", 
   "merge_fields": {
      "FNAME": "Urist", 
      "LNAME": "McVankab"
   }
}

And the following root endpoint for the API lists resource:

https://<dc>.api.mailchimp.com/3.0/

So here's my form.submit() code with the jQuery Ajax POST request:

$(document).ready(function(){
    var mcForm = $('#mailchimpForm');
    var mailchimp = {};
    mailchimp.dc='us5';
    mailchimp.id='xxxxxxxx';
    var url = '//' + mailchimp.dc + '.api.mailchimp.com/3.0/lists/' + mailchimp.id + '/members/';

    function beginMailchimpPost(data){
        var params = JSON.stringify(data);
        $.ajax({
            url: url,
            method: 'POST',
            data: params,
            dataType: 'jsonp',
            contentType: 'application/json; charset=utf-8',
            error: function(res, text){
                console.log('Err', res);
            },
            success: function(res){
                console.log('Success', res);
            }
        });
    }
});

This is the JSON.stringify(data) object:

{"email_address":"email@mail.com","status":"subscribed","merge_fields":{"FNAME":"Name","LNAME":"Last name"}}

And I'm getting the following error:

GET http://... 401 (Unauthorized)
Err Object {readyState: 4, status: 404, statusText: "error"}

What could be wrong?

Here's the link to Mailchimp's API v3.0 docs (list members collection).

ekad
  • 14,436
  • 26
  • 44
  • 46
Gus
  • 6,545
  • 4
  • 36
  • 39

4 Answers4

3

Unfortunately it is not possible to make requests for the front-end Mailchimp API.

Note MailChimp does not support client-side implementation of our API using CORS requests due to the potential security risk of exposing account API keys.

https://developer.mailchimp.com/documentation/mailchimp/guides/get-started-with-mailchimp-api-3/#authentication

2

The way I did it is to use your AJAX code but strip out all the MailChimp stuff and send the post data to a PHP file. I used this code:

https://github.com/actuallymentor/MailChimp-API-v3.0-PHP-cURL-example/blob/master/mc-API-connector.php

I just stripped out everything but the part I needed for subscribing a single user and it worked like a charm. For error reporting, you can probably detect for errors on the PHP side and send HTTP status to the AJAX.

David Rhoderick
  • 356
  • 1
  • 5
  • 19
-1

You're getting a 401 because you're not passing in your API key.

You'll need to add the following to you're ajax call:

beforeSend: function(xhr) { xhr.setRequestHeader("Authorization",
    "Basic " + btoa("api:" + mailchimp_api_key)); };

Where mailchimp_api_key is the key for your account. Take a look at http://kb.mailchimp.com/api/article/api-3-overview for more information on auth with the api.

aubreyrhodes
  • 777
  • 4
  • 16
  • 3
    But also: if this is from clientside JS, there's going to be a cross-site scripting problem here as well. Calls need to be proxied through a server rather than relying on the client. – TooMuchPete Sep 25 '15 at 17:59
  • @TooMuchPete so there's no easy way of posting to mailchimp through the client? There are a lot of jQuery/Angular plugins using API v2.0 that do this. – Gus Sep 26 '15 at 08:56
  • @aubreyhodes thanks for your reply but now I'm getting a 404. I added the right API as well. No success. – Gus Sep 26 '15 at 10:05
  • 4
    The client-side JavaScript libraries I've seen typically either proxy requests through the server or post to the form submission end-point instead of using the authenticated API. Aside from the the technical limitations, you don't want to send clients your API key because that gives every visitor to your site complete access to your account. – TooMuchPete Sep 27 '15 at 13:47
  • 5
    ^^ This. **Do not use your API key on the browser**. Your API key should be kept secret. – miguelv May 05 '17 at 10:55
-2

You need to add your API key in params, like this;

{
   "apikey": "your key here",
   "email_address": "urist.mcvankab@freddiesjokes.com", 
   "status": "subscribed", 
   "merge_fields": {
      "FNAME": "Urist", 
      "LNAME": "McVankab"
   }
}

Then you need to change datetype from "jsonp" to "json". "jsonp" is GET only and will not work with POST method.

And the last thing you need to do is to allow for cross domain scripting;

http://enable-cors.org/server.html