132

Is there any way to integrate mailchimp simple (one email input) with AJAX, so there is no page refresh and no redirection to default mailchimp page.

This solution doesn't work jQuery Ajax POST not working with MailChimp

Thanks

6
  • after submitting the form it redirects to mailchimp "confirm" page.
    – alexndm
    Dec 8, 2011 at 15:45
  • 3
    your solution has huge security hole, API key should be treated as private since it does provide full access to your MailChimp account. #justsaying
    – user1178634
    Jan 30, 2012 at 17:34
  • 1
    That solution exposes your mailchimp API which is not a good idea Mar 18, 2012 at 19:54
  • 3
    Doens't the default HTML embed option on mailchimp's website expose your api key also? It can't be any better or worse then that solution.
    – Bob Bobbio
    Dec 4, 2012 at 22:00
  • Use this jquery plugin: github.com/scdoshi/jquery-ajaxchimp
    – sid
    May 4, 2013 at 2:01

10 Answers 10

259

You don't need an API key, all you have to do is plop the standard mailchimp generated form into your code ( customize the look as needed ) and in the forms "action" attribute change post?u= to post-json?u= and then at the end of the forms action append &c=? to get around any cross domain issue. Also it's important to note that when you submit the form you must use GET rather than POST.

Your form tag will look something like this by default:

<form action="http://xxxxx.us#.list-manage1.com/subscribe/post?u=xxxxx&id=xxxx" method="post" ... >

change it to look something like this

<form action="http://xxxxx.us#.list-manage1.com/subscribe/post-json?u=xxxxx&id=xxxx&c=?" method="get" ... >

Mail Chimp will return a json object containing 2 values: 'result' - this will indicate if the request was successful or not ( I've only ever seen 2 values, "error" and "success" ) and 'msg' - a message describing the result.

I submit my forms with this bit of jQuery:

$(document).ready( function () {
    // I only have one form on the page but you can be more specific if need be.
    var $form = $('form');

    if ( $form.length > 0 ) {
        $('form input[type="submit"]').bind('click', function ( event ) {
            if ( event ) event.preventDefault();
            // validate_input() is a validation function I wrote, you'll have to substitute this with your own.
            if ( validate_input($form) ) { register($form); }
        });
    }
});

function register($form) {
    $.ajax({
        type: $form.attr('method'),
        url: $form.attr('action'),
        data: $form.serialize(),
        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) {
            if (data.result != "success") {
                // Something went wrong, do something to notify the user. maybe alert(data.msg);
            } else {
                // It worked, carry on...
            }
        }
    });
}
22
  • 10
    I made a jquery-plugin that uses this method: github.com/scdoshi/jquery-ajaxchimp
    – sid
    Jul 6, 2013 at 2:53
  • 23
    You can also use JSONP. Use the post-json as described. Remove the &c= if You have it in the form action url. Use dataType: 'jsonp' and jsonp: 'c' for Your jQuery ajax call.
    – czerasz
    Sep 5, 2013 at 12:41
  • 6
    Note that the email form fields must have name="EMAIL" for mailchimp to process
    – Ian Warner
    Feb 7, 2014 at 12:08
  • 6
    Just FYI in case anyone is having issues, the name of the email parameter should be EMAIL (all caps). Otherwise you will get an error stating that the email address is blank. Mar 3, 2015 at 16:03
  • 6
    Has MailChimp disabled this method of accessing the API since this answer was written? I seen no indication in the documentation that a GET/POST without the API key can subscribe a user to a list.
    – Greg Bell
    Jul 31, 2015 at 6:13
35

Based on gbinflames' answer, I kept the POST and URL, so that the form would continue to work for those with JS off.

<form class="myform" action="http://XXXXXXXXXlist-manage2.com/subscribe/post" method="POST">
  <input type="hidden" name="u" value="XXXXXXXXXXXXXXXX">
  <input type="hidden" name="id" value="XXXXXXXXX">
  <input class="input" type="text" value="" name="MERGE1" placeholder="First Name" required>
  <input type="submit" value="Send" name="submit" id="mc-embedded-subscribe">
</form>

Then, using jQuery's .submit() changed the type, and URL to handle JSON repsonses.

$('.myform').submit(function(e) {
  var $this = $(this);
  $.ajax({
      type: "GET", // GET & url for json slightly different
      url: "http://XXXXXXXX.list-manage2.com/subscribe/post-json?c=?",
      data: $this.serialize(),
      dataType    : 'json',
      contentType: "application/json; charset=utf-8",
      error       : function(err) { alert("Could not connect to the registration server."); },
      success     : function(data) {
          if (data.result != "success") {
              // Something went wrong, parse data.msg string and display message
          } else {
              // It worked, so hide form and display thank-you message.
          }
      }
  });
  return false;
});
0
21

For anyone looking for a solution on a modern stack:

import jsonp from 'jsonp';
import queryString from 'query-string';

// formData being an object with your form data like:
// { EMAIL: '[email protected]' }

jsonp(`//YOURMAILCHIMP.us10.list-manage.com/subscribe/post-json?u=YOURMAILCHIMPU&${queryString.stringify(formData)}`, { param: 'c' }, (err, data) => {
  console.log(err);
  console.log(data);
});
2
  • This worked, even though Firefox might try to block the request from leaving by its Enhanced Protection. You can also skip importing 'query-string' package by supplying your own encoder like this: function queryString(data) { return Object.keys(data).map((key) => `${encodeURIComponent(key)}=${encodeURIComponent(data[key])}`).join('&'); } (skip the .stringify method then)
    – Knogobert
    Jan 11, 2021 at 12:53
  • Although implied, taking this answer to the next level by including: import serialize from form-serialize'; let formData = serialize(e.target); to get that data out of a form and into an object and only passing in the object as a string to the URL https://...&${formData} queryString.stringify() - is not needed as of 2021
    – grantmx
    Feb 11, 2021 at 11:13
20

You should use the server-side code in order to secure your MailChimp account.

The following is an updated version of this answer which uses PHP:

The PHP files are "secured" on the server where the user never sees them yet the jQuery can still access & use.

1) Download the PHP 5 jQuery example here...

http://apidocs.mailchimp.com/downloads/mcapi-simple-subscribe-jquery.zip

If you only have PHP 4, simply download version 1.2 of the MCAPI and replace the corresponding MCAPI.class.php file above.

http://apidocs.mailchimp.com/downloads/mailchimp-api-class-1-2.zip

2) Follow the directions in the Readme file by adding your API key and List ID to the store-address.php file at the proper locations.

3) You may also want to gather your users' name and/or other information. You have to add an array to the store-address.php file using the corresponding Merge Variables.

Here is what my store-address.php file looks like where I also gather the first name, last name, and email type:

<?php

function storeAddress(){

    require_once('MCAPI.class.php');  // same directory as store-address.php

    // grab an API Key from http://admin.mailchimp.com/account/api/
    $api = new MCAPI('123456789-us2');

    $merge_vars = Array( 
        'EMAIL' => $_GET['email'],
        'FNAME' => $_GET['fname'], 
        'LNAME' => $_GET['lname']
    );

    // grab your List's Unique Id by going to http://admin.mailchimp.com/lists/
    // Click the "settings" link for the list - the Unique Id is at the bottom of that page. 
    $list_id = "123456a";

    if($api->listSubscribe($list_id, $_GET['email'], $merge_vars , $_GET['emailtype']) === true) {
        // It worked!   
        return 'Success!&nbsp; Check your inbox or spam folder for a message containing a confirmation link.';
    }else{
        // An error ocurred, return error message   
        return '<b>Error:</b>&nbsp; ' . $api->errorMessage;
    }

}

// If being called via ajax, autorun the function
if($_GET['ajax']){ echo storeAddress(); }
?>

4) Create your HTML/CSS/jQuery form. It is not required to be on a PHP page.

Here is something like what my index.html file looks like:

<form id="signup" action="index.html" method="get">
    <input type="hidden" name="ajax" value="true" />
    First Name: <input type="text" name="fname" id="fname" />
    Last Name: <input type="text" name="lname" id="lname" />
    email Address (required): <input type="email" name="email" id="email" />
    HTML: <input type="radio" name="emailtype" value="html" checked="checked" />
    Text: <input type="radio" name="emailtype" value="text" />
    <input type="submit" id="SendButton" name="submit" value="Submit" />
</form>
<div id="message"></div>

<script src="jquery.min.js" type="text/javascript"></script>
<script type="text/javascript"> 
$(document).ready(function() {
    $('#signup').submit(function() {
        $("#message").html("<span class='error'>Adding your email address...</span>");
        $.ajax({
            url: 'inc/store-address.php', // proper url to your "store-address.php" file
            data: $('#signup').serialize(),
            success: function(msg) {
                $('#message').html(msg);
            }
        });
        return false;
    });
});
</script>

Required pieces...

  • index.html constructed as above or similar. With jQuery, the appearance and options are endless.

  • store-address.php file downloaded as part of PHP examples on Mailchimp site and modified with your API KEY and LIST ID. You need to add your other optional fields to the array.

  • MCAPI.class.php file downloaded from Mailchimp site (version 1.3 for PHP 5 or version 1.2 for PHP 4). Place it in the same directory as your store-address.php or you must update the url path within store-address.php so it can find it.

3
  • 2
    If you just want to add a signup form to your site and submit it via AJAX, @gbinflames's answer works. Just tried it myself. Apr 6, 2014 at 1:01
  • 1
    No, there is no must.
    – Nowaker
    Jun 30, 2014 at 13:41
  • 2
    Crap, I gotta say - I implemented @skube's answer a while ago on a site and then later added site-wide https. Just discovered now that it's not working with the mailchimp http AJAX call. Highly recommend going with this method right off the bat if you site might ever need or consider using SSL. Aug 26, 2016 at 4:10
6

Based on gbinflames' answer, this is what worked for me:

Generate a simple mailchimp list sign up form , copy the action URL and method (post) to your custom form. Also rename your form field names to all capital ( name='EMAIL' as in original mailchimp code, EMAIL,FNAME,LNAME,... ), then use this:

      $form=$('#your-subscribe-form'); // use any lookup method at your convenience

      $.ajax({
      type: $form.attr('method'),
      url: $form.attr('action').replace('/post?', '/post-json?').concat('&c=?'),
      data: $form.serialize(),
      timeout: 5000, // Set timeout value, 5 seconds
      cache       : false,
      dataType    : 'jsonp',
      contentType: "application/json; charset=utf-8",
      error       : function(err) { // put user friendly connection error message  },
      success     : function(data) {
          if (data.result != "success") {
              // mailchimp returned error, check data.msg
          } else {
              // It worked, carry on...
          }
      }
5

As for this date (February 2017), it seems that mailchimp has integrated something similar to what gbinflames suggests into their own javascript generated form.

You don't need any further intervention now as mailchimp will convert the form to an ajax submitted one when javascript is enabled.

All you need to do now is just paste the generated form from the embed menu into your html page and NOT modify or add any other code.

This simply works. Thanks MailChimp!

6
  • 5
    It will really help if you can add some article link/ blog posts for doing the same Mar 2, 2017 at 18:15
  • 1
    I have added Mailchimp embed code into my html page but Ajax doesn't automatically work as suggested above. I get redirected to another page. How can I make this work without a redirect?
    – Petra
    Aug 23, 2017 at 11:38
  • 1
    In the MailChimp admin go to your list -> Signup Forms -> Embedded forms -> Classic. You'll see that there is some JS included in the code snippet. This will enable form validation and AJAX submission.
    – MarcGuay
    Nov 24, 2017 at 21:57
  • 1
    using the mailchimp code - how do i plug a custom action to the ajax success ? [like hiding the form]
    – Adeerlike
    Aug 13, 2018 at 13:46
  • 1
    @Masiorama I opted for removing the mc-validate script, as it also contained an old jquery and was too big and vulnerable. so just having html validation and submitting with ajax like in stackoverflow.com/a/15120409/744690
    – Adeerlike
    Oct 31, 2018 at 18:38
4

Use jquery.ajaxchimp plugin to achieve that. It's dead easy!

<form method="post" action="YOUR_SUBSCRIBE_URL_HERE">
  <input type="text" name="EMAIL" placeholder="e-mail address" />
  <input type="submit" name="subscribe" value="subscribe!" />        
  <p class="result"></p>
</form>

JavaScript:

$(function() {
  $('form').ajaxChimp({
    callback: function(response) {
      $('form .result').text(response.msg);
    }
  });
})
0
1

I wasn't able to get this working with fetch so had to combine a few answers here using GET and parsing form inputs into the query string for the URL. It also wasn't necessary for the name of the input to be EMAIL but I guess it makes it more legible and doesn't break the code (in this simple case. Play around if you have other form fields).

Here's my code;

<form action="https://me.usxx.list-manage.com/subscribe/post-json?" id="signup" method="GET">
  <input type="hidden" name="u" value="xxxxxxxxxxxxxxxxxx"/>
  <input type="hidden" name="id" value="xxxxxxxxx"/>
  <input type="hidden" name="c" value="?"/>
  <input name="EMAIL" type="text" />
</form>
// Form submission handler
const formData = new FormData(signup);

fetch(signup.action + new URLSearchParams(formData).toString(), {
  mode: 'no-cors',
  method: signup.method,
})
.then((res) => {
  // Success
})
.catch((e) => {
  // Error
})

You could make it no-js friendly with...

<form action="https://me.usxx.list-manage.com/subscribe/post" id="signup">
fetch(signup.action + '-json?' + new URLSearchParams(formData).toString(), {

And just to save those who fumbled around as I did needlessly, you must create a signup form for an Audience within Mailchimp and by visiting that page you can get your u value and id as well as the action. Maybe this was just me but I thought that wasn't explicitly clear.

2
  • To follow up on more experimenting, Using Fetch, we don't get access to the returned JSON object so if a user signs up twice, we can't tell them to update their profile (like mailchimp would) nor can we warn them of any messages such as the one I received during testing "too many signups". These errors succeed in the eyes of fetch so frankly I would avoid using it. I just didn't want to download another library to my site but managed to find a standalone AJAX to keep it as lean as possible. Feb 5, 2022 at 14:52
  • Hi, I'm getting an error "too many attemps using this email adress". Have you had this problem ? Nov 9 at 16:18
1

This Github code works perfectly for me. This has a detailed explanation of how to use it. I use it on my WP site. Here is the link - https://gist.github.com/DmitriyRF/34f659dbbc02637cf7465e2efdd37ef5

0

In the other hand, there is some packages in AngularJS which are helpful (in AJAX WEB):

https://github.com/cgarnier/angular-mailchimp-subscribe

1

Not the answer you're looking for? Browse other questions tagged or ask your own question.