78

I'm new to MailChimp and need some help.

With their basic newsletter signup form... you simply embed some prepackaged HTML into your page. However the problem with this is that clicking on submit redirects to a MailChimp page. (I don't want to redirect to MailChimp, I want the user to stay on own website after hitting submit.)

They provide an API and plenty of documentation but just about zero useful examples. The API is supposed to allow me to do a full integration with my site or application. It seems that when I read something in their docs that applies to me, I click the link to get more information and I end up going around in circles. They tell you how to do it but they fail to "show" you how to it.

I can get an API Key, they have tons of documentation, and a whole bunch of wrappers & plugins... PHP, Drupal, Wordpress, etc...

The confusion here regarding their pre-packaged solutions is that I just have a regular static HTML page, it's not Wordpress, PHP, or Drupal... so I just don't know where to start ... I don't even know if I'm supposed to use POST or GET.

I'm not a newbie to API's... I do very well with getting the Google Maps API to do whatever I want. However, Google provides real-world working examples in addition to their detailed documentation which is how I learned it. I just want to see it in action before I can grasp the finer points of the API.

Without any solid examples or tutorials in their online documentation, I'm asking how to create the most basic HTML signup form using their API.

ekad
  • 14,436
  • 26
  • 44
  • 46
Sparky
  • 98,165
  • 25
  • 199
  • 285
  • I'm not sure that the API is what you need for just a simple HTML page. Have you tried just to embed your form? http://kb.mailchimp.com/article/how-can-i-add-my-signup-form-on-my-website – Dan Esparza Jul 10 '13 at 14:48
  • @DanEsparza, of course you need the MailChimp API. Otherwise, your form will always redirect to a MailChimp page, which is exactly the problem I'm solving here. – Sparky Jul 10 '13 at 15:41
  • Sorry, I guess I was thrown by the sentence, "The problem is that I just have a regular page I created with HTML, not wordpress, not php, not drupal... I just don't know where to start" – Dan Esparza Jul 10 '13 at 19:41
  • @DanEsparza, no worries. _"don't know where to start"_ was in reference to the second paragraph which defines the problem, _"the problem is that it (their basic newsletter signup form) is not very smart. Clicking on submit opens a window with a Mailchimp url, etc."_ – Sparky Jul 10 '13 at 20:07
  • @DanEsparza, I see how I used _"the problem is"_ twice which can be misleading. I'll edit for clarification. – Sparky Jul 10 '13 at 20:16

3 Answers3

75

EDITED:

Since posting this answer MailChimp has released version 2 & 3 of their API. Version 3 will be the only supported version starting in 2017. As soon as I have a chance to test it, I will update this answer for API version 3.


MailChimp API v3.0

As per notification at the top of this page, all prior versions of the API will not be supported after 2016.

My solution uses PHP in the background for handling the API, and jQuery to facilitate the Ajax.

1) Download a PHP wrapper that supports API v3.0. As of this writing, there is nothing official listed in the latest MailChimp docs that supports v3.0, but several are listed on GitHub, so I selected this one.

2) Create the following PHP file, store-address.php, using your own API key and list ID, and then place it in the same directory as the wrapper from step one. Remember to follow the documentation for your wrapper, but they all seem fairly similar to this.

<?php // for MailChimp API v3.0

include('MailChimp.php');  // path to API wrapper downloaded from GitHub

use \DrewM\MailChimp\MailChimp;

function storeAddress() {

    $key        = "xxxxxxxxxxxxxxx-us1";
    $list_id    = "xxxxxx";

    $merge_vars = array(
        'FNAME'     => $_POST['fname'],
        'LNAME'     => $_POST['lname']
    );

    $mc = new MailChimp($key);

    // add the email to your list
    $result = $mc->post('/lists/'.$list_id.'/members', array(
            'email_address' => $_POST['email'],
            'merge_fields'  => $merge_vars,
            'status'        => 'pending'     // double opt-in
            // 'status'     => 'subscribed'  // single opt-in
        )
    );

    return json_encode($result);

}

// If being called via ajax, run the function, else fail

if ($_POST['ajax']) { 
    echo storeAddress(); // send the response back through Ajax
} else {
    echo 'Method not allowed - please ensure JavaScript is enabled in this browser';
}

3) Create your HTML/CSS/JavaScript(jQuery) form (It is not required to be on a PHP page, and the visitor will never see that PHP is being used in the background.)

The response is in JSON so you'll have to handle it correctly.

Here is what my index.html file looks like:

<form id="signup" action="index.html" method="get">
    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" />
    <input type="submit" id="SendButton" name="submit" value="Submit" />
</form>
<div id="message"></div>

<script src="jquery.min.js"></script>
<script>
$(document).ready(function() {
    $('#signup').submit(function() {
        $("#message").html("Adding your email address...");
        $.ajax({
            url: 'inc/store-address.php', // proper url to your "store-address.php" file
            type: 'POST', // <- IMPORTANT
            data: $('#signup').serialize() + '&ajax=true',
            success: function(msg) {
                var message = $.parseJSON(msg),
                    result = '';
                if (message.status === 'pending') { // success
                    result = 'Success!  Please click the confirmation link that will be emailed to you shortly.';
                } else { // error
                    result = 'Error: ' + message.detail;
                }
                $('#message').html(result); // display the message
            }
        });
        return false;
    });
});
</script>

MailChimp API version 1:

(original answer)

After fumbling around for a while, I found a site using the PHP example with jQuery. From that I was able to create a simple HTML page with jQuery containing the basic sign-up form. The PHP files are "hidden" in the background where the user never sees them yet the jQuery can still access & use.

1) Download the PHP 5 jQuery example here... (EDIT: links are dead. However, the only important part is the official API wrapper for PHP which is available 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'])) {
        // 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 what my index.html file looks like:

<form id="signup" action="index.html" method="get">
    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"></script>
<script>
$(document).ready(function() {
    $('#signup').submit(function() {
        $("#message").html("Adding your email address...");
        $.ajax({
            url: 'inc/store-address.php', // proper url to your "store-address.php" file
            data: $('#signup').serialize() + '&ajax=true',
            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.

Sparky
  • 98,165
  • 25
  • 199
  • 285
  • Notice - If you get a 500 server error, you might not have php curl installed. `apt-get install php-curl` should fix it (On Ubuntu 16.04) – Nitay Oct 28 '16 at 20:50
20

Here is an example using version 2.0 of Mailchimp API together with mailchimp-api (a minimal php abstraction class for dealing with the Mailchimp API).

<?php

include('MailChimp.php');

$MailChimp = new MailChimp('API_KEY');
$result = $MailChimp->call('lists/subscribe', array(
    'id'                => 'LIST_ID',
    'email'             => array( 'email' => $_POST['email'] ),
    'merge_vars'        => array(
        'MERGE2' => $_POST['name'] // MERGE name from list settings
        // there MERGE fields must be set if required in list settings
    ),
    'double_optin'      => false,
    'update_existing'   => true,
    'replace_interests' => false
));

if( $result === false ) {
    // response wasn't even json
}
else if( isset($result->status) && $result->status == 'error' ) {
    // Error info: $result->status, $result->code, $result->name, $result->error
}

?>

Read more about what you can send with the API call at the MailChimp API Documentation.

Toby Allen
  • 10,997
  • 11
  • 73
  • 124
Jonas Äppelgran
  • 2,617
  • 26
  • 30
  • Thanks Jonas. I've downloaded the mailchimp api package using the link that you have provided. However I can only find a file called MailChimp.php, and not MailChimp.class.php like on the 2nd line of your code. Do I need to rename the file to add the wry "class" before the php extension? Thanks – Greg May 28 '14 at 14:19
  • Hi Greg, there's no need for the .class.php extension. I guess the package owner simply has renamed the file. It was named MailChimp.class.php when I wrote the answer. I will update the answer with the current filename. – Jonas Äppelgran May 29 '14 at 16:12
  • Latest MailChimp uses Namespace... new /Drewm/MailChimp('API_KEY'); – Adam Mills Mar 08 '15 at 04:32
8

Here's another example of using version 2.0 of the Mailchimp API using the Official PHP Wrapper.

The difference between my example and others posted here is that I'm using the subscribe method of the Mailchimp_Lists class, accessible through instantiation of the Mailchimp class (->lists), rather than the generic call method.

$api_key = "MAILCHIMP_API_KEY";
$list_id = "MAILCHIMP_LIST_ID";

require('Mailchimp.php');
$Mailchimp = new Mailchimp($api_key);
$subscriber = $Mailchimp->lists->subscribe($list_id, array('email' => $_POST['email']));

if ( ! empty($subscriber['leid'])) {
    // Success
}
davidnknight
  • 462
  • 4
  • 7
  • If you're just using the Lists, did you have the require all of the files that are at the top of `Mailchimp.php`? – chris_s Jan 29 '14 at 16:30
  • And if you use MERGE vars, just add them like: $merge_vars = array( "FNAME"=>"name", "CUSTOMMRG" => "test123" ); $Mailchimp_Lists->subscribe( $list_id, array( 'email' => $_POST['email'] ), $merge_vars ); – Mladen Janjetovic May 20 '14 at 16:08
  • Hi, for some reason I'm getting this error message. Would you know why? Fatal error: Class 'Mailchimp' not found in /homez.527/dqsdsq/www/desdsqd.com/newsletter/subscribe.php on line 6 – Greg May 28 '14 at 15:54
  • @Greg maybe you didn't include('Mailchimp.php') or require(Mailchimp.php) file. – aesede Aug 06 '14 at 23:03
  • @chris_s You probably could look to remove/comment out some of them, I haven't looked to be honest. But you will need the main Mailchimp.php as an instantiation of itself must be passed when instantiating Mailchimp_Lists. – davidnknight Dec 12 '14 at 09:56
  • @aesede Definitely a require, otherwise your script will only fatal error anyway when it tries to access a property/method on a none object, so might as well have it error at the point of inclusion. – davidnknight Dec 12 '14 at 09:58