MailChimp Subscribe Form with PHP, jQuery and AJAX (API 3.0)

MailChimp Subscribe Form with PHP, jQuery and AJAX (API 3.0)

By popular demand, I updated my code and posted it as new GitHub repository that utilizes newer MailChimp API 3.0. Please read the tutorial below to create AJAX based MailChimp subscribe form on your PHP website with a little jQuery knowledge.

Original post using (older and no longer supported) MailChimp API 1.0 can be found here.

What this code does

  • Validate field contents
  • Pass the form submission to MailChimp and add the record to your list
  • Basic fallback method for very, very old browser or does not have JavaScript activated
  • Very customizable and easily expandable, depending on your requirements
  • jQuery and jQuery Validation plugin called from CDNJS to keep number of files to maintain at minimal

Tools/Credits

  1. jQuery
  2. jQuery Validation Plugin
  3. MailChimp API v3 PHP Wrapper

MailChimp API Key and List ID

Below we start, we need to generate public API key from your MailChimp account and also identify your list ID. If you are not sure how to retrieve those, follow these links from MailChimp Knowledge Base to retrieve your account’s API key and find your list ID.

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.

For this example, I am including first name and last name as part of the form fields. Feel free to make adjustments as required. Although keep in mind after changing the form fields, you may also need to adjust the subscribe.php  file too.

<html>
<head>
  <title>MailChimp (API v3) Sign-Up Form</title>
  <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
  <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/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)

I try to include as much comment as possible to make the code self explanatory.

<?php

  // Put your MailChimp API and List ID hehe
  $api_key = 'ENTER_YOUR_API_KEY_HERE';
  $list_id = 'ENTER_YOUR_LIST_ID_HERE';

  // Let's start by including the MailChimp API wrapper
  include('./inc/MailChimp.php');
  // Then call/use the class
  use \DrewM\MailChimp\MailChimp;
  $MailChimp = new MailChimp($api_key);

  // Submit subscriber data to MailChimp
  // For parameters doc, refer to: http://developer.mailchimp.com/documentation/mailchimp/reference/lists/members/
  // For wrapper's doc, visit: https://github.com/drewm/mailchimp-api
  $result = $MailChimp->post("lists/$list_id/members", [
              'email_address' => $_POST["email"],
              'merge_fields'  => ['FNAME'=>$_POST["fname"], 'LNAME'=>$_POST["lname"]],
              'status'        => 'subscribed',
            ]);

  if ($MailChimp->success()) {
    // Success message
    echo "<h4>Thank you, you have been added to our mailing list.</h4>";
  } else {
    // Display error
    echo $MailChimp->getLastError();
    // Alternatively you can use a generic error message like:
    // echo "<h4>Please try again.</h4>";
  }
?>

Download

Click here to download the basic files to create MailChimp subscribe form on your website. Alternatively, you can also visit the GitHub repository.

Coming Soon Templates

The MailChimp subscribe form example only includes 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.

38 Comments MailChimp Subscribe Form with PHP, jQuery and AJAX (API 3.0)

  1. Pierce

    Hi Micheal,

    Thanks for this. I’m testing it on a local server and getting no response from the form except a console error:
    POST [mydomain]/mailchimptest/subscribe.php 500 (Internal Server Error)

    Finding that a bit difficult to debug. Everything seems to be in the right place and I think I’ve put in valid API and list IDs.
    Any tips?

    thanks,
    -Pierce

    Reply
    1. Michael

      Hi Pierce – It is a bit difficult to provide insights as the code is currently installed on your local server. But based on the information you provided, shouldn’t the POST URL be on localhost instead of your domain?

      Reply
      1. Pierce

        Hi Micheal, thanks for getting back.

        Sorry, it’s not actually on localhost, rather webhosting with a domain. Sorry for the badly worded question.

        Mailchimp-api is partly working, as I wrote a simple api call in the subscribe.php to print out my lists using the api-key. Where it fails is when I try to do the Mailchimp->post of the “email_address” and “status”. All the post values (I’m only passing email address) seem to be there in subscribe, available.

        Guess I was hoping you’d tell me the API had changed in the last few months or something. But looking at their docs it looks like this should work…

        Might try it in a different server in case it’s local settings.

        Reply
        1. Michael

          To be honest, I have not tested this code for quite a while now. However based on your further confirmation, if you were able to call the API for different commands, then it should be working. Have you tried enabling double opt-in? Not really sure if it is related or not though.

        2. Pierce

          Thanks Micheal, I got diverted from this in the last few days but will have another go shortly. Will let you know if I discover anything that pertains to your example.

  2. alenm88

    When someone tries to signup with an email that already exists in the list you get the error of please use a valid email… is there a way to ignore the fact that someone already sign up or display a custom message for this case?

    thank you

    Reply
    1. Michael

      The email format validation should not relate to whether the email already exists on the mailing list or not. Do you have a preview link so me to check?

      Reply
  3. Tony

    When I run the script, I get the following error:

    Parse error: syntax error, unexpected ‘[‘ in /home/xxx/public_html/xxx/mailchimp/subscribe.php on line 16

    I’m running PHP v 5.3.16 / MySQL 5.1.54

    Is this normal behavior?

    Reply
    1. Michael

      It should be working without refresh. You may want to double check the JS part of the index.php to make sure all has been set correctly. Also check the browser console to see if it shows any error or warning.

      Reply
      1. Marco

        Ok thanks for the reply. I’ve scoured the Internet, and couldn’t find a solution anywhere. The refresh works in your example, but I have added radio buttons to my form that allows you to choose one of three interest groups/categories that I have created in my Mailchimp List. By pure luck, I have the form working and it submits with the correct interests category. BUT, I cant get the darn thing to submit without refresh.

        This isn’t my forte, but my arrogance (or stupidity depending on perspective), is determined to figure this out. browser console gives me this error:

        Uncaught TypeError: (o.dataType || “*”).toLowerCase is not a function

        Here is the code I was able to stumble into :
        https://gist.github.com/anonymous/d1858a846d382482c6c27cacb6d4db93

        I know you are probably a busy man, but I need help from a Jedi. Obi Wan you’re my only hope. Honestly, any help or direction you can give me, would be much appreciative.

        Reply
        1. Luis

          Hi Marco,
          i am facing a similiar issue. U have a list of checkboxes and i am trying to pass the interests to Mailchimp. Did you manage your script to work? Would appreciate it to have a look on your result. Thank you! 🙂

        2. Michael

          Hi Marco – Sorry for the late reply. I missed the notification for your last comment somehow. I think the problem you are having is related to the HTML and jQuery syntax. You cannot have more than one element with the same IDs. So for each radio button you need to assign a unique idea. Then you create a condition logic to identify which radio that is selected and pass the value to subscribe.php.

  4. Nate

    I absolutely love this. Is there a way of applying the same script to work with WordPress comment subscriptions too, based on a checkbox value? So if I check a box underneath the comment form, it will subscribe me to the Mailchimp list? Also, is there a way where I can feed the API key and list with an externally set variable, like say a WordPress option key?

    Reply
  5. Rebecca

    Hello, thanks for sharing this. It works great! Is there a way to load the ‘#response’ back onto the parent page (index.php) without a refresh? Your help will be ecstatically appreciated!

    Reply
    1. Michael

      Hi Rebecca – If you set the AJAX correctly, then the response message should be loaded on the parent page without a refresh. Unless you are referring to a different behavior.

      Reply
    1. Michael

      It’s quite hard to determine the problem without having access to the code. The only advice I can give for now is to try looking at your MailChimp API calls history/log. It is under Account > Extras > API Keys.

      Reply
      1. totalnoob

        I got this error too. All I had changed from the code provided is the API Key and List ID, which I confirmed were right. When I called getLastResponse() it returned ‘Array’… do you have any suggestions based on that information?

        Reply
        1. Michael

          Most likely this is a syntax issue. Could you paste your subscribe.php here? You can screen out the last few digits of the API key and list ID.

  6. Asti

    Hi, really like your explainations, Thank you. I would like to add a double Opt-in. Could you guide me to add it? It would be great! Thanks again.

    Reply
    1. Michael

      Hi, it’s actually quite simple to enable double opt-in. Just change the `status` array when posting the email address to `pending` instead of `subscribed`.
      'status' => 'pending'

      Reply
  7. Fredrik

    I get the error message
    Parse error: syntax error, unexpected ‘[‘ in /home/xxx/public_html/xxx/mailchimp/subscribe.php on line 16
    How can this be solved?

    Reply
  8. doudou

    Hi, very great work you have done here, However I would like to know how can we Clear all input fields after submission of data? and how can we display error message inside every inputs ?

    Thanks in advance

    Reply

Leave a Reply