Search code examples
jqueryajaxgetmailchimpmailchimp-api-v3.0

Mailchimp connection error (401) with Api v3.0 and jQuery Ajax method


I'm trying to connect an html page with my Mailchimp (free) account. I've read the documentation and should be quite simple.

This is my JS code (jQuery 1.2.2 loaded on page load):

username = [your-username];
apiKey = [your-mailchimp-api-key];
baseUrlMailchimp = "https://us5.api.mailchimp.com/3.0/";
apiMC = function(type, data, url, callback) {
            $.ajax({
                type: type,
                dataType: 'jsonp',
                data: data,
                contentType: 'application/json',
                url: url,
                beforeSend: function(xhr) {
                    xhr.setRequestHeader('Authorization', 'Basic ' + btoa(username + ":" + apiKey));
                },
                success: function(e) {
                    if (callback) {
                        callback(e)
                    }
                },
                error: function(e) {
                    console.log(e);
                }
            });
        }
apiMC('GET', '', baseUrlMailchimp + 'lists', function(res){console.log(res)})

The problem is that I receive an error 401 (Your request did not include an API key).

If I launch the same request from my Chrome REST client:

http://restclient.net/

specifying the url and user/api in the basic auth fields, everything works fine!

I cannot understand why, can anyone help me?

UPDATE: ANSWER FROM MAILCHIMP

Hey there Francesco,

I took a look at the article link provided and it does look like you are running into a same Origin policy block. The same origin policy prevents ajax from calling its non-origin domains. Because of this you would need to use a server side method to fire off API calls.

Also, at this time MailChimp does not support Jsonp for API 3.0.

If there is anything else at all with which I can assist, please do not hesitate to reach back out to support.

END


Solution

  • I think you might be running into Same Origin Policy. I don't think you can call another domain from AJAX. You will likely need to implement your call server side, maybe through a gateway file.

    https://en.wikipedia.org/wiki/Same-origin_policy