Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mailchimp subscribe using jQuery AJAX?

What is a complete jQuery solution to subscribing uses to a list on Mailchimp?

The problem is that most solutions either use a library or require server side code. I want a quick elegant solution, which gives me complete control over the UI, hence UX of the form and it's functionality.

like image 635
Nagra Avatar asked Feb 03 '14 11:02

Nagra


2 Answers

@Nagra's solution is good but it will throw an error when executed from the client's browser due to the Same-Origin Security Policies in effect. In essence, these security measures are there to prevent cross site requests that occur when the originator and the sender are on different domains.

If you see errors like the below in the javascript console it is a clear indication.

XMLHttpRequest cannot load http://YOUR-MAILCHIMP-URL. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin http://BROWSER-LOCATION is therefore not allowed access.

To overcome this problem the script needs to be rewritten to utilize CORS or JSONP. As the MailChimp API does not support CORS the only option is the undocumented JSONP interface.

Change the URL to utilize the /subscribe/post-json? version and also append &c=? to the end. Once the URL is updated you will also need to modify the dataType in the JSON hash to be jsonp

The updated first few lines of the function should resemble the below.

$.ajax({
    url: '//YOUR URL&id=YOUR LIST ID&c=?',
    data: $('#YOUR FORM').serialize(),
    dataType: 'jsonp',
like image 101
nneko Avatar answered Nov 10 '22 07:11

nneko


  1. Obtain the URL for the list by selecting the List > Sign Up forms > (Classic form). You will find it on the 'Copy/paste onto your site' textarea and it will most likely begin with your username.

    $('#your-form').submit(function (e) {
        e.preventDefault();
    
        $.ajax({
            url: 'YOUR URL',
            type: 'GET',
            data: $('#your-form').serialize(),
            dataType: 'jsonp',
            contentType: "application/json; charset=utf-8",
            success: function (data) {
               if (data['result'] != "success") {
                    //ERROR
                    console.log(data['msg']);
               } else {
                    //SUCCESS - Do what you like here
               }
            }
        });
    });
    
like image 37
Nagra Avatar answered Nov 10 '22 07:11

Nagra