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

Community
  • 1
  • 1
alexndm
  • 2,899
  • 5
  • 24
  • 25

10 Answers10

258

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...
            }
        }
    });
}
Sam
  • 2,771
  • 2
  • 28
  • 41
gbinflames
  • 2,812
  • 1
  • 16
  • 8
  • 10
    I made a jquery-plugin that uses this method: https://github.com/scdoshi/jquery-ajaxchimp – sid Jul 06 '13 at 02: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 05 '13 at 12:41
  • 6
    Note that the email form fields must have name="EMAIL" for mailchimp to process – Ian Warner Feb 07 '14 at 12:08
  • Note that it is a GET request not a post. This answer still works great. – inorganik Apr 22 '14 at 19:32
  • is validate_input a function somewhere? – v3nt Nov 25 '14 at 16:21
  • Yes, validate_input is a function defined elsewhere, it's used to validate the users input before submitting the form but it's not really relevant to the answer so it was omitted to keep things as simple as possible. – gbinflames Dec 01 '14 at 18:26
  • The method from @sid was the only one I could get working: http://github.com/scdoshi/jquery-ajaxchimp — Thanks! – kevnk Dec 03 '14 at 14:50
  • 1
    Can you unsubscribe someone using this same method? – kevnk Dec 03 '14 at 15:50
  • 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. – Nick Tiberi Mar 03 '15 at 16:03
  • 1
    If using jQuery it'd be better to .bind() to the form's submit event rather than the click event: `$form.submit(function (event) {...});` – Warpling May 13 '15 at 08:20
  • 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 '15 at 06:13
  • When I use this method, server returns success message but the user is not subscribed (does not appear in list of subscribers)? – Ross Aug 06 '15 at 21:21
  • 1
    I just tried this and can confirm it still works. By default, MailChimp doesn't add a new signup to your "list" until they confirm via their email address - FYI. And you can access the message returned by MailChimp in your `success` block using `data.msg` (so you can JQuery the response message to your form). – evolross Oct 14 '15 at 21:36
  • Thanks for the code, but i am getting Could not connect to server error. Do you have any idea about this error? – Pratik Deshmukh Jul 27 '16 at 10:10
  • Thanks for this snippet! Still works well and i'm using a POST method. Not sure why it would be a GET request. Can someone elaborate on this? Any links to MailChimp documentation? – phip Jan 19 '17 at 21:43
  • 1
    @grsmto posted a better alternative. – ricricucit Feb 25 '19 at 14:13
  • Anyone else getting a 403 Forbidden response while using this answer, these days? Might just be my code but I'm not sure. – Lewis May 20 '20 at 16:28
  • 1
    @Beaniie I used this method on a project last month and it works perfectly. – Jay Oct 07 '20 at 15:39
  • Just a note of caution that this technique may not work for users with certain content blockers installed. The disconnect.me browser plugin for example blocks network calls to mailchimp by default and simulates a 307 redirect for such calls. If you use this approach you may consider warning the user about content blockers if your error handler is called. – Mike Vosseller Dec 30 '20 at 18:24
  • used 5 yeasr ago. used today. still gold. – Adeerlike Apr 26 '21 at 10:51
  • 3
    Trying to do this with a fetch() doesn't work because of cors error. – Drew Baker May 19 '21 at 22:33
  • 1
    @DrewBaker Just pass mode: "no-cors" - that helped me out with cors issue – Klimenko Kirill Jan 14 '22 at 03:12
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;
});
skube
  • 5,867
  • 9
  • 53
  • 77
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: 'emailofyouruser@gmail.com' }

jsonp(`//YOURMAILCHIMP.us10.list-manage.com/subscribe/post-json?u=YOURMAILCHIMPU&${queryString.stringify(formData)}`, { param: 'c' }, (err, data) => {
  console.log(err);
  console.log(data);
});
adriendenat
  • 3,445
  • 1
  • 25
  • 25
  • 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 '21 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 '21 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.

Community
  • 1
  • 1
Sparky
  • 98,165
  • 25
  • 199
  • 285
  • 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. – Patrick Canfield Apr 06 '14 at 01:01
  • 1
    No, there is no *must*. – Nowaker Jun 30 '14 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. – squarecandy Aug 26 '16 at 04: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...
          }
      }
Reza Hashemi
  • 1,768
  • 14
  • 13
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!

Doody P
  • 4,611
  • 2
  • 20
  • 18
  • 5
    It will really help if you can add some article link/ blog posts for doing the same – gonephishing Mar 02 '17 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 '17 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 '17 at 21:57
  • Confirmed working by default today. In the 'Classic' embed form, there are some options under 'Enhance your form', one of which is "*Disable all javascript* This disables field validation, and inline form submission. The form will submit to your hosted subscribe form." This suggests that 'inline submission' (ie. AJAX) is the default. – Ben Hull Jul 30 '18 at 13:17
  • 1
    using the mailchimp code - how do i plug a custom action to the ajax success ? [like hiding the form] – Adeerlike Aug 13 '18 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 https://stackoverflow.com/a/15120409/744690 – Adeerlike Oct 31 '18 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);
    }
  });
})
Nowaker
  • 12,154
  • 4
  • 56
  • 62
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

Mostafa Barmshory
  • 1,849
  • 24
  • 39
0

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.

  • 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. – Samuel Gregory Feb 05 '22 at 14:52