MailChimp Subscribe Form with PHP, jQuery and AJAX

MailChimp Subscribe Form with PHP, jQuery and AJAX

I am pretty sure I have mentioned somewhere in this blog or tweets of how I love MailChimp or and would recommend it for any business wanting to untap their email marketing potential. You can start with zero investment and only start paying when you are completely confident it is very worthy.

MailChimp provides a good tool to generate your custom sign up form which will serve most requirements well. Some customers however, want a fully custom form or integrate it with existing template they already own. Today I am going to share a quick tutorial in how to integrate HTML form with MailChimp API using PHP and jQuery.

MailChimp Subscribe Form Features

What will it do?

  • Validate field contents
  • Pass the form submission to MailChimp and add the record to your list
  • Basic fallback method for very, very old browser that does not have JavaScript activated
  • Five minutes setup

Tools/Credits

  1. jQuery
  2. jQuery Validation Plugin
  3. MailChimp PHP API Class

The Form Page (index.php)

jQuery will handle the AJAX using $.post method and jQuery Validation plugin will validate the field values including email address format.

<html>
<head>
  <title>MailChimp Sign-Up Form</title>
  <script type="text/javascript" src="js/jquery-1.11.0.min.js"></script>
  <script type="text/javascript" src="js/jquery.validate.min.js"></script>
  <script type="text/javascript">
    $(document).ready(function() {
      // jQuery Validation
      $("#signup").validate({
        // if valid, post data via AJAX
        submitHandler: function(form) {
          $.post("subscribe.php", { fname: $("#fname").val(), lname: $("#lname").val(), email: $("#email").val() }, function(data) {
            $('#response').html(data);
          });
        },
        // all fields are required
        rules: {
          fname: {
            required: true
          },
          lname: {
            required: true
          },
          email: {
            required: true,
            email: true
          }
        }
      });
    });
  </script>
</head>

<body>
  <div id="wrapper">
    <form id="signup" class="formee" action="subscribe.php" method="post">
      <fieldset>
        <legend>Sign Up</legend>
        <div>
          <label for="fname">First Name *</label> <input name="fname" id="fname" type="text" />
        </div>
        <div>
          <label for="lname">Last Name *</label> <input name="lname" id="lname" type="text" />
        </div>
        <div>
          <label for="email">Email Address *</label> <input name="email" id="email" type="text" />
        </div>
        <div>
          <input class="right inputnew" type="submit" title="Send" value="Send" />
        </div>
      </fieldset>
    </form>
    <div id="response"></div>
  </div>
</body>
</html>

Form Processor (subscribe.php)

Our form will connect to MailChimp with the help of MCAPI.class.php. Please make sure you have generated the API key of your account and copied your list ID. MailChimp’s excellent knowledge base provides the instructions in how to retrieve your account’s API key and find your list ID.

<?php
  require_once 'inc/MCAPI.class.php';
  $api = new MCAPI('ENTER_YOUR_API_KEY_HERE');
  $merge_vars = array('FNAME'=>$_POST["fname"], 'LNAME'=>$_POST["lname"]);

  // Submit subscriber data to MailChimp
  // For parameters doc, refer to: http://apidocs.mailchimp.com/api/1.3/listsubscribe.func.php
  $retval = $api->listSubscribe( 'ENTER_YOUR_LIST_ID_HERE', $_POST["email"], $merge_vars, 'html', false, true );

  if ($api->errorCode){
    echo "<h4>Please try again.</h4>";
  } else {
    echo "<h4>Thank you, you have been added to our mailing list.</h4>";
  }
?>

That’s it! You can now check on your web server with a few tests and see if they are captured in your MailChimp list.

Download

Sample files and structure of this tutorial can be downloaded here. Please share this post if you find it useful using social media buttons below.

Coming Soon Templates

My files only include a basic HTML page. If you are thinking of using it for your upcoming site, and you have limited resources to create the page design, check out my list of 5 Clean and Free Coming Soon Page Templates and Coming Soon & Under Construction Templates on ThemeForest.


UPDATE (January 9, 2017)

I have published updated version of this tutorial to make use of MailChimp’s newer API 3.0. Please follow the link to read how to create MailChimp Subscribe Form with PHP, jQuery and AJAX (API 3.0).

127 Comments MailChimp Subscribe Form with PHP, jQuery and AJAX

  1. Laveena

    Hello MICHAEL,
    Thank You so much for your wonderful post.I used this code but their is one issue i am facing… the code is working fine on local server but it is not working on live.it showing me “Please try again. error code -99”.
    please help me to sort this issue. i will be greatfull to you.!!

    Reply
    1. Michael

      Hello Laveena – Error code 99 might indicate an issue with local networking. You may want to try looking into the API endpoint URL. Ensure it is already correct and match to your MailChimp’s API details.

      Reply
  2. Justin Zhang

    Hi, Michael – Thanks for your reply about the outdated code for API 3.0.
    For excellent PHP wrapper of MailChimp’s API 3.0, the instruction is so professional, and I could not make the demo code with PHP and Jquery and ajax by myself, so could you help me to provide a demo with PHP wrapper? Or you could submit a post, and every one could read it.
    Thanks very much, and wish you have a nice day.

    Reply
    1. Michael

      Hi Justin – I’ve been planning to write an updated post make use the v3 wrapper, but haven’t found the time for it yet. While MailChimp API v1 is officially deprecated, it is still fully working. I’ll put a note when the updated post is ready.

      Reply
  3. Brandon Powell

    Hey Michael,

    I have two question, So everything work with no error message. When I type name, email, and submit the form It’s says “Please Try again” want know what I did wrong so I understand how to fix the problem. I’m new using Mailchimp API.

    Thank you,
    Brandon P

    Reply
    1. Michael

      Hey Brandon – “Please try again” error message indicates that was a problem when submitting the data through MailChimp API. It’s a bit hard to debug the actual problem without having access to the form and MC account unfortunately.

      Reply
  4. James

    Is there a way to modify this to only send email? Can I remove the merged fields (name, name)? I’m also using bootstrap css to “skin” my form, so do I just change the form ID to match what I have?. And lastly, all I want to do is redirect to another URL after the submit button is clicked. I know in main chimp to do single opt-in, you can change the variable from “pending” to “subscribed”. How do I setup the url redirect? Thanks.

    Reply
    1. Michael

      Hi James – Yes, you can remove the name fields. It is not required by MailChimp API to add new subscriber. You will also need to adjust the jQuery validation and subscribe.php to reflect the removal of the name fields.

      To do redirect upon successful submission, you to edit the subscribe.php and jQuery code too.

      $(document).ready(function() {
      	// jQuery Validation
      	$("#signup").validate({
      		// if valid, post data via AJAX
      		submitHandler: function(form) {
      			$.post("subscribe.php", { email: $("#email").val() }, function(data) {
      				if(data != "success") {
      					$('#response').html(data); // tell user there is a problem
      				} else {
      					window.location.href = "http://www.yourdomain.com/redirect-page/";
      				}
      			});
      		},
      		// all fields are required
      		rules: {
      			email: {
      				required: true,
      				email: true
      			}
      		}
      	});
      });
      
      <?php
      require_once 'inc/MCAPI.class.php';
      $api = new MCAPI('[[YOUR_API_KEY]]');
      // $merge_vars = array('FNAME'=>$_POST["fname"], 'LNAME'=>$_POST["lname"]);
      $merge_vars = array();
      
      // Submit subscriber data to MailChimp
      // For parameters doc, refer to: http://apidocs.mailchimp.com/api/1.3/listsubscribe.func.php
      $retval = $api->listSubscribe( '[[YOUR_LIST_ID]]', $_POST["email"], $merge_vars, 'html', false, true );
      
      if ($api->errorCode){
      echo "<h4>Please try again.</h4>";
      } else {
      echo "success";
      }
      ?>
      Reply
      1. James

        Thanks for updated code. There are a couple of questions. 1. Can I substitute my mail chimp.php (which is the v3 api for mail chimp for the MCAPI? 2. in the php code you still have:
        $retval = $api->listSubscribe( ‘ENTER_YOUR_LIST_ID_HERE’, $_POST[“email”], $merge_vars, ‘html’, false, true );

        Can I remove the $merge_vars since we commented them out above?

        3. Is there way to move the jscript to the js folder instead of being buried in the html of index? that way it further protects what the end user can see in source?

        Thanks.

        -James

        Reply
        1. Michael
          1. I don’t think it’s going to work, but feel free to try.
          2. You still need to put a parameter there, probably a false value. Refer to MailChimp API docs
          3. If you’re familiar with jQuery and JS in general, you can move it to an external JS file. But the inline code does not have any sensitive information (like the API key), so it should be relatively safe.
  5. Mark WIltshire

    Hi Michael,

    This is a fantastic post, thank you.

    I have hit a couple of small issues.
    a) Location or return message:
    I have the BASIC script working well, and the when I test, the message comes back after the form.
    BUT when I add a radio button, it now, for some reason posts on a different page -> i.e. the AJAX call doesn’t seem to now work??

    b) Then Error message for the radio button validation seems to appear between the 2 radio buttons
    How can I change this?

    You can see this on my DEV server http://www.kinkoo.co.uk

    Any ideas why these problems are happening.

    many thanks

    Mark

    Reply
    1. Michael

      Hi Mark,

      I think the AJAX function failed to run because it cannot get the value of gender radio button. Could you try to update the submitHandler by adding .val() after gender: $('input[name="gender"]:checked')?

      submitHandler: function(form) {
          $.post("subscribe.php", { fname: $("#fname").val(), lname: $("#lname").val(), email: $("#email").val(), gender: $('input[name="gender"]:checked').val() }, function(data) {
              $('#response').html(data);
          });
      },
      
      Reply
  6. Peter

    Hi Michael,
    there is one more thing I would like to change. As Edward Beecroft I would also like to use a Bootstrap modal popup. I have studied your first response on this:

    “You should instead change the jQuery script in the index.html and replace $(‘#response’).html(data); with the code line to call the modal box.”

    And then I had a look at

    http://www.w3schools.com/bootstrap/bootstrap_modal.asp

    But unfortunetly I don’t konw what to do. Could you give me any further help how to manage this?

    Many thanks.

    Reply
    1. Michael

      Hi Peter – Could you share a link to your development page? It is quite difficult to help without actually seeing how the HTML is coded.

      Reply
  7. Peter

    Hey,

    thank you very much! Now it works!!! The double opt in – the subscriptions beeing not confirmed – was the problem.

    Absolutely fantastic !!!

    Question: If I decide to write a tutorial how I managed to get this run in WordPress, would you mind if I paste a link here? (this will probably take a while)

    Reply
    1. Michael

      Hi Peter – Glad you managed to sort it out. Of course you can share tutorial in how to implement this on WordPress. There were readers asking about it, so it would be helpful. Looking forward to reading your guide when it is ready.

      Cheers.

      Reply
  8. Peter

    Hi Michael,

    thank you very much.That was a great hint. In the API calls log I can see every activity that I did yesterday. So something is happaning there. But I still don’t see any email adresses in my list. (the list is configured to sign-in only with an email, but in my homepage I have activated double opt-in).

    Now first question I have: Why can I not assign one of the two lists that I have created to the API Key? How does it get decided to which list the subscribers are added with this particular API Key? I couldn’t find any selection in Mailchimp.

    Second question I have: Do I have to configure the double opt-in email in ailchimp? Or is it generated automatically? Do the subscribers somehow show up in the list as pending (or similar status) until they get confirmed? Or do they not show up at all?

    BTW: Have you read this on the Mailchimp API Docs

    “MailChimp API v3.0 is now live! Prior versions will no longer be supported after 2016, so all API users should begin transitioning to v3.0. Check out the API v3.0 Documentation for more details. ”

    Question: Will your solution still work after 2016?

    Many thanks for your help.

    Best
    Peter

    Reply
    1. Michael

      Q1: This is probably the hint why your list is not updating. Have you put the correct list ID on the script? The API key is to access your entire account and you need to define the list ID when the email address should be subscribed to.

      Q2: You can define the double-opt in from MailChimp’s interface. However when you are subscribing the email address through API then you can overrule the default setting. If I’m not mistaken, subscription which has not been confirmed will not be listed.

      This tutorial actually only utilizes MailChimp API v1.3, so it is more dated than you think but still working. I do not believe MailChimp will deactivate deprecated APIs though. They are just no longer supported, as in you cannot contact them if you are having problems with the API connection etc.

      Reply
  9. Peter

    Hi Michael,
    great tutorial !!! I just have a question: How long does it take untill a new email is shown in the mailchimp list? I have waited now for 8 hours but nothing happend. Everything seems to be working fine. I even get the message “Thank you, you have been added to our mailing list.”. Is there anything elese I have to check? Maybe some configuration in MailChimp? I have never created a form within Mailchimp though. So maybe Mailchimp is not ready yet?

    OR … – Currently I am still devloping my first project of this type. Therefore it is all local. It’s based on Wamp (local server), WordPress (locally) Bootstrip (including jQuery 1.11.3). … could it be that all of this solution is not working locally – for what ever reason?

    I am a little bit lost at the moment. Since everything seems to be wording – even with WordPress I have managed, which was a big hassle – I do not really know where to start searching. Do you have a good hint?

    Many thanks!

    Reply
    1. Michael

      Hi Peter – If it is working, the subscription should happen instantaneously. Although sometimes when you check on your list, the number of subscribers may still the same because it is cached. It should also work on local server, as long as you have active Internet connection and the server is allowed to connect to the web.

      The first thing you could check is the API calls log. Go to Account > Extras > API keys from your MailChimp admin, the same panel to create your API key, then scroll down to the bottom. If the API was triggered correctly, it should list the activity there.

      Reply
    1. Michael

      It’s possible. There are a few ways to do this, but below is what I think would be the simplest approach.

      On index.php, replace the submitHandler function like this:

      // if valid, post data via AJAX
      submitHandler: function(form) {
          $.post("subscribe.php", { fname: $("#fname").val(), lname: $("#lname").val(), email: $("#email").val() }, function(data) {
              $('#response').html(data);
              if (data.toLowerCase().indexOf("thank you") >= 0) { // if success, it should have a 'thank you' substring
                  window.location.href="http://www.yourwebsite.com/redirect-page";
              }
          });
      },
      
      Reply
    1. Michael

      Magento has very complex framework and I would advise against trying to modify the template files unless you have extensive knowledge with this e-commerce platform. You are better trying to find an extension which allows to add this functionality.

      Reply
  10. Sai

    Hi,

    Thanks for the post. How to make this form to act as a popup when visitor visits the website. Can you please share your valuable knowledge on this.

    Reply
    1. Michael

      Hi Sai – In order for you to combine this with a popup script, you will need to have solid understanding how it works separately. But once you get it, it is actually quite easy. You could embed the form as hidden inline element or iframe and put pretty much the same HTML code and it should work.

      Unfortunately it is going to be quite difficult to provide real example as there are hundreds of popup scripts and each of them has different behavior and configuration.

      Reply
  11. Yannick

    Hi,
    Thank you for your post, it was really helpful and helped me get started.

    I have been all day tryning all day to add radio button to my form.
    My form validation is OK, the email adress is added to mailchimp, but nothing in my new field 🙁

    Maybe you can help me out ?

    Thanks !

    In my index.php file I have :

    my form :

    Particulier :
    Professionnel :

    My function :

    $(document).ready(function() {
    $(“#signup”).validate({
    submitHandler: function(form) {
    $.post(“subscribe.php”, { typeClient: $(‘input[name=”MMERGE3″]:checked’, ‘#signup’).val(), email: $(“#email”).val() }, function(data) {
    $(‘#response’).html(data);
    });
    },
    });
    });

    and finaly in my subsribe.php :

    require_once ‘inc/MCAPI.class.php’;
    $api = new MCAPI(‘API_KEY’);
    $merge_vars = array(‘typeClient’=>$_POST[“typeClient”]);
    $retval = $api->listSubscribe( ‘LIST_ID’, $_POST[“email”], $merge_vars, ‘html’, false, true );

    Reply
    1. Michael

      This is a wild guess, but I think you were confused between the variables used by HTML form/jQuery and ones that should be sent to MailChimp:

      In your index.php:

      $.post("subscribe.php", { typeClient: $('input[name="NAME_OF_CHECKBOX_FIELD"]:checked', '#signup').val(), email:

      Then use MMERGE3 in subscribe.php:

      $merge_vars = array('MMERGE3'=>$_POST["typeClient"]);

      Also make just the values you put under NAME_OF_CHECKBOX_FIELD are 100% match to the ones you set on MailChimp.

      Let me know if this helps.

      Reply
  12. Robion

    Hey there, Really love this setup that you have built. However when a user subscribes to the list I have, they dont get a notification, and nor do i?

    Reply
        1. Michael

          On subscribe.php file, change this line:

          $retval = $api->listSubscribe( '[[YOUR_LIST_ID]]', $_POST["email"], $merge_vars, 'html', false, true );

          into this:

          $retval = $api->listSubscribe( '[[YOUR_LIST_ID]]', $_POST["email"], $merge_vars, 'html', false, true, true, true );

          Actually the parameter is not part of merge_vars but the listSubscribe itself.

  13. Husain

    The script displays the message “Thank you, you have been added to our mailing list” but no subscriber was actually added to the list when I check the admin panel.

    Reply
    1. Michael

      Hi Husain – MailChimp sometimes caches the subscribers data displayed on the admin so it may not always get updated in real time. Have you tried to check it again? Also if the list is set to use double opt-in, please make sure you received the confirmation email and have verified the subscription.

      Reply
  14. Ricardo

    Hi Michael – First of all thank you! I’ve found this tutorial so helpful, it’s just what I needed and haven’t found anything like this before. After some tweaks it works like a charm for my purposes.

    I would suggest remove the [[ and ]] on API KEY and LIST ID, because it took me some time to figure out it was unnecesary, and seems to be I’m not the only one.

    I would like to know if there is any way to encrypt or hide the API Key in subscribe.php file, because I think anyone with a web inspector could get it and maybe ruin your lists.

    Thanks!

    Reply
    1. Michael

      Hi Ricardo – Thanks for sharing your feedback. Happy to hear you find this tutorial useful. I have taken your suggestion and removed the brackets to make it less confusing for users to enter their API and list ID.

      Regarding the API key in subscribe.php, it will not be viewable by end users. PHP is server side scripting which means unless you tell the code to display an output, the rest of the code is completely invisible. Only if a person has access to the FTP of course, but that is a much more serious security breach you will need to worry about should it happen 🙂

      Cheers!

      Reply
      1. Ricardo

        Hi again Michael,

        Thanks for responding so quickly!

        Ok, now I get it, my fault. This is due to my total ignorance about PHP behavior, haha.

        Thanks again for your guidance 🙂

        Cheers!

        Reply
    1. Michael

      Hi Philipp – Thanks for dropping by. I have been wanting to post another tutorial for MailChimp API v3 but always missed to dedicate the time for it. Will keep you posted when I have finally managed to do it. Cheers.

      Reply
  15. Edward Beecroft

    Hmmm. This is unknown territory in my Javascript knowledge. So I have made the modal pop-up in HTML/CSS. I have currently linked it to the button, which means it pops up whenever the button is clicked – irrespective of whether the submission to the Mailchimp List was successful.

    I would be so enormously grateful if you could try and help here – I’m so near the end, I can almost taste victory! ha! Presumably I need to write code that only makes the modal box appear when the submission is successful?

    Thanks,
    Ed

    Reply
  16. Edward Beecroft

    So….I went away and made some changes. First of all I actually downloaded the MCAPI file and put that in. I also bought a hosting package as I will need one anyway, and didn’t want my problems to be caused by local hosting. Now, I am at the stage where I am getting ‘Please try again’ message.

    I would like to confirm, in the MCAPI file, how should this line look?

    $api = new MCAPI(‘[[API KEY HERE’]]); – I took this from above.

    I ask only because a user said that he had too many brackets….and there’s a lot of brackets there! Same goes for the List ID, do we need [[ and ]] each side of the number?

    Many thanks!

    Reply
    1. Edward Beecroft

      EDIT! It works!! I removed the [[ and ]] from both the API Key section and the List ID section.

      I now want to change the success message so that the page doesn’t change, but instead there is a small modal popup (i’m using bootstrap) that confirms the subscription. Basically, I don’t want the page to change, I want the user to be notified of the subscription, then let them minimize the modal window and carry on browsing.

      I don’t need help with the HTML/CSS/Bootstrap design, but I am guessing I will need to change something in the ‘echo’ of the else statement in subscribe.php?

      Any help is HUGELY appreciated! Thanks!

      Reply
      1. Michael Sunarlim

        Hi Ed – Great job in putting the pieces together yourself! You do not need to change the echo to make it work with Bootstrap’s modal. You should instead change the jQuery script in the index.html and replace $('#response').html(data); with the code line to call the modal box.

        When you have a problem. You need to test by calling the modal box by itself (without involving the form), then copy the working code into the submitHandler function.

        Reply
  17. Edward Beecroft

    Firstly, let me thank you immensely for this! This is the kind of post so many people wish to see but can never find.

    At the moment I have built the website (HTML/CSS). I have built the signup form etc into the homepage. Do I still need to create an index.php file or can I just place this into the index.html file? If I do need an index.php file….how should I go about this? (Remember the form is already built in the HTML file).

    Please excuse me if this question is downright foolish! Thanks!

    Reply
    1. Michael

      Hi there Edward – Since we are using AJAX, you can keep the index file in HTML format. However your server needs to support PHP in order for the server side script (subscribe.php) to work. JQuery’s function will handle the response provided by subscribe.php to display whether the subscription is successful or not, even if the index page is only in HTML. That’s the beauty of AJAX.

      Give it a shot and let me know if you find any problem in making it work on your website’s environment.

      Reply
      1. Edward Beecroft

        Hi Michael,

        Thanks for the speedy response. So I have merged the code with my HTML file and created the subscribe.php file. I have also edited the code to remove the name fields. At the moment I am encountering an issue similar to a user above (Suresh) – where I was being redirected to subscribe.php after submitting the form. I am currently using jquery-1.11.1.js – not the ‘min’ version. Could this be the issue?

        Otherwise I will try using the older version included in the git repo.

        Thanks again.

        Reply
        1. Michael

          Hi Edward – Could you try testing the code using the older jQuery included in the repo, as you suggested? Honestly I have not tried to test the code with latest version of jQuery. Please share if that solves the issue, that probably means there has been a change in jQuery AJAX method and I will try to update my code to work with newer jQuery.

          Thanks.

  18. Ady

    Hello Michael,
    Thank you very much for Great Tutorial, My Question is What if I want to add another field how I will handle it on subscribe.php and I noticed my email Field Name is all capital i.e EMAIL in mailchimp but in subscribe.php it is all lowercase.
    Here is my form structure on Mailchimp with their names.

    Full Name = FNAME
    Email = EMAIL
    Car Plate No = CARPLATE

    I have these 3 fields I tried to subscribe I got success message as well but still waiting for Confirmation email, I think there is difference in name of Email Field.
    Can you please Guide me.

    Reply
    1. Michael

      Hi Ady – First off, the $_POST[""] is only relevant to the field names on your form. The email field itself should not be included under $merge_vars, instead it should be included on $api->listSubscribe itself.

      Based on the details you provided, these would be the edits:

      $merge_vars = array('FNAME'=>$_POST["FNAME"], 'CARPLATE'=>$_POST["CARPLATE"]);$retval = $api->listSubscribe( '[[YOUR_LIST_ID]]', $_POST["EMAIL"], $merge_vars, 'html', false, true );
      

      If you got a success message, most likely you already did things right though. Have you checked on your spam folder?

      Reply
  19. Josh

    Great tutorial, Michael. I’ve been a little stuck on the final piece. Validation messages work great, but I keep getting the “please try again” response. Is there any way to see the error code coming back from MC to help troubleshoot? I’m on my local server too – not sure if that matters.

    Reply
      1. Josh

        Thanks! Unfortunately, I got “-99” which is Unknown_Exception. The only undocumented one :-O. At least I know I’m getting a response from MC

        Reply
        1. Josh

          Yeah, I had a couple extra brackets messing up the syntax…my error code changed to “270” List_InvalidInterestGroup. Looking into that now

        2. Josh

          Fixed it! For some reason, line 8 was chopped up a bit in subscribe.php. Changing it back to:
          $retval = $api->listSubscribe( ‘[[YOUR_LIST_ID]]’, $_POST[“email”], $merge_vars, ‘html’, false, true );
          did the trick!

    1. Michael

      Hi Naomi – Integrating with groups can be done by modifying the $merge_vars variable (line 4 on subscribe.php). So it would become something like this:

      $merge_vars = array('FNAME'=>$_POST["fname"], 'LNAME'=>$_POST["lname"], 'GROUPINGS' => array(array('name' => '[Group_Name]', 'groups' => '[Group_Option_Name]')));

      Replace [Group_Name] and [Group_Option_Name] accordingly based on how you set up your MailChimp list groups. For example:

      'GROUPINGS' => array(array('name' => 'Interest', 'groups' => 'Food'))

      More information about variables that you can set can be found on MailChimp API documentation: https://apidocs.mailchimp.com/api/1.3/listsubscribe.func.php

      Reply
      1. naomi

        That’s very helpful. Thanks so much Michael! I think I got this part set correctly, but now I’m not sure how to pass the values from the form to the api. Do you know how I can do that too?

        Reply
        1. Michael

          It depends on how you set up the form. In case you use then just set the right form element name and pass it to the processor.

          Form

          
          

          jQuery

          $.post("subscribe.php", { fname: $("#fname").val(), lname: $("#lname").val(), email: $("#email").val(), interest: $("#interest").val() }, function(data) // the rest remains the same

          Processor

          'GROUPINGS' => array(array('name' => 'Interest', 'groups' => $_POST["interest"]))
  20. Dazzy

    Can we use multiple forms (e.g in header, footer, sidebar) or do we need to change the Ids of the fields without breaking any functionality?

    Reply
    1. Michael

      If you want to use in multiple forms, you can consider changing the jQuery call to from ID $("#signup") into a class: $(".someclass"). Then make sure you put the class name into every form that links to MailChimp API.

      Reply
    1. Michael

      Hi – “Please try again” error means there is something wrong when connecting to the API. Can you double check if the API and LIST ID’s are correct?

      Additionally, you can try to print the $api->errorCode to get more information about the error.

      Reply
  21. Kelly

    Hi There. Thanks for this! I’ve successfully implemented on my website. However, I’m wondering if there’s a way to have the confirmation message return on the same page as the form, or redirect to a new page after a successful subscription. Right now, it’s opening a new window and displaying the message, which is kind of annoying.

    Reply
  22. kalpafit6

    Dear All,
    I’m using PHP MailChimp API 2.0 to integrate with my Symfony2 Application. I’m using a check box to subscribe user to a mailchimp account. It’s working fine. We are providing a facility to change their preferred email address in our application. Now in our database the preferred email is different from the mailchimp api’s email address. So if the user resubscribe from my application i need to update the users new email address. So I’m passing leid instead of email in this case. But this change is not reflecting in mailchimp account. Some times it’s reflecting after few hours. Could any one please help me.

    $response = $mc_lists->updateMember(
    // $mailChimpAccount->getListId(),
    // $email,
    // $merge_vars,
    // $email_type = ‘text’,
    // $double_optin = false,
    // $update_existing = true,
    // $replace_interests = true
    //// $send_welcome = false
    // );

    For $email If it’s a new user subscription Im passing $email = array(’email’=>$_post[’email’]) and if it’s a existing email update Im passing $email=array(‘leid’=> ‘leid of the email’)

    Reply
    1. Michael

      Hi – If the update is reflected on MailChimp in the end, even though it is only shown a few hours later, it appears to be working. I believe MailChimp caches the subscribers data when you browse it through the admin. So it may not be best to check on the changes through the admin view, instead you should try to query through the API also.

      Reply
    1. Michael

      Hi – Thanks for bringing this up. The #response element was not included in the index.php. I have updated this on the git repo, please re-download the files. I placed it right after </form> but you basically can put the <div id="response"></div> anywhere.

      Reply
      1. suresh

        After integration code in my webpage.response message was coming in another page(subscribe.php).but in your ample files that was in same page(indexpage).how to resolve this.

        Reply
        1. Michael

          Hi Suresh – If you get redirected to subscribe.php after submitting the form, that means the AJAX is not working. You should check if the jquery-1.11.0.min.js path is correct in your project folder and called properly.

      2. suresh

        Thank You sir.

        It’s working after removing jquery-1.11.1.What to do if i want to keep this latest version.

        Reply
        1. Michael

          I don’t think you need to use the latest version of jQuery. If it is working with older version, that is fine and you do not need to worry. You could try to use newest version that still works with your script, moving back one minor version at a time. Alternatively, try to validate your HTML code in case that was the cause why jQuery 1.11.1 didn’t work.

  23. Noob

    Hi, I am very new to this. May I know how I should change the code in subscribe.php if I only want to take the users email, without their first and last name?

    Reply
    1. Michael

      Hi there – To disable first name and last name requirement, you need to remove these lines from index.php:

      fname: {
      required: true
      },
      lname: {
      required: true
      },

      And from subscribe.php change $merge_vars = array('FNAME'=>$_POST["fname"], 'LNAME'=>$_POST["lname"]); to $merge_vars = array();

      Reply
  24. Akshith

    Hi,

    Do you know how to send campaign to individual subscribed users using mailchimp on php. Hence I am gettting some issues. Below is the scenario

    Scenario :

    1.Able to add an user to the list on Mailchimp, after that I am able to approve campaign(business template) through mailchimp to the new user.
    2.Then I have tried adding another user to the mailchimp list, successfully added to the list. But when the campaign is approved, MailChimp API returns an error:

    “Unable to send campaign id d********5 to the email: mail id. Errror Code=313 Msg=This Campaign has already been sent and cannot be sent again.”

    Can you please help me on this.

    Reply
    1. Michael

      Hi Akshith – The issue you are facing is beyond the scope of this post, but I will try to help within my limitation. Based on your explanation, it seems that you were trying to send one campaign multiple times to different segments and MailChimp disallowed that. Instead of using campaigns, have you tried on using autoresponder (automation) instead?

      Reply
  25. Jonathan Mahan

    I’d rather not use a plugin, due to their “dumbed-down” nature. Not to mention they usually add a ton of features I will never use, causing the plugin to not be lightweight. I’ll take a look into that one though, thanks.

    Reply
    1. Michael

      An understandable reason. However well built plugins to connect to other great services through API like MailChimp’s should not take too much of server resources. While I have not used it myself, judging from the reviews, MailChimp for WordPress appears to be a solid plugin.

      Feel free to share your impressions here again after you have tried it.

      Reply
    1. Michael

      Hi Akshith – Can you share what version of PHP are you running? Also you can try removing the AJAX part of the code to see if it returns with any message.

      // if valid, post data via AJAX
      submitHandler: function(form) {
          $.post("subscribe.php", { fname: $("#fname").val(), lname: $("#lname").val(), email: $("#email").val() }, function(data) {
              $('#response').html(data);
          });
      },
      
      Reply
  26. Shannon T.

    First of all, thank you for this great piece of code! It works perfectly for me and the information is stored in MailChimp correctly, but I have only one problem …when I click “Submit” on the form, I don’t get any success message displayed. The form stays there like nothing happened even though the information is stored in MailChimp. Any ideas what’s wrong?

    Reply
    1. Michael

      Hi Shannon – Glad to hear this code helped you in integrating with MailChimp. As for your issue, can you share a link to the test page so I can look into it?

      Reply
  27. Jonathan

    How can I go about implementing this on a WordPress site? I’m a noob when it comes to Javascript and PHP. Any help would be appreciated!

    Reply
    1. Michael

      Hi Glen – Unfortunately the code is still based on MailChimp API v1.3. However I do not think MailChimp is going to remove support to older APIs anytime soon. Version 2 offer lots of new call methods, but we probably won’t need them for simple integration like discussed on this post.

      Reply
  28. Marko

    Thank You for fast respons 😀
    I found a link in line 7, and make it work’s.
    My fault that I have not found immediately.
    Just to know, I found some solution on the internet that are not good, but your’s is great.

    Great post, keep it that way!

    Reply
      1. Marko

        Hi Michael 😀
        One question, do I need to upload .DS_Store file too, or not?

        And, can you make example, or tutorial (beather) for Contact Form whit PHPMailer 😀

        Reply
        1. Michael

          Hi Marko – You can ignore .DS_Store files, or delete them. It is Mac OS X’s folder data and is not used in any way by the web server.

          PHPMailer is quite an extensive class, the way to use it depends on the requirements. One example may not be applicable to all situations. If you need to integrate PHPMailer to your existing page, maybe I can help by taking a look at it.

  29. Marko

    Thank you very much, your post was excellent.
    I have one question, how to enable sending confirmation link to subscribers.
    In this case, subscribers are automatically added to the list, without sending a confirmation link to them.
    Everything else works great!
    Thank you very much!

    Reply
    1. Michael

      Hi Marko – Glad you find the post useful and thank you for posting your comment.
      To enable double opt-in is very easy. Just change line 8 of subscribe.php to:

      $retval = $api->listSubscribe( '[[YOUR_LIST_ID]]', $_POST["email"], $merge_vars, 'html', true, true );

      The fifth variable is for ‘double_optin’ option for MailChimp’s listSubscribe API.
      Let me know how that works out for you.

      Reply

Leave a Reply