MailChimp form using API v3.0 and jQuery ajax

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

I created a simple HTML page for a dynamic MailChimp sign-up form using jQuery ajax. This means that your users can signup for your MailChimp list without leaving your page. Better than that, they will signup without a page refresh, as the jQuery and `ajax()` will dynamically update the page with the response from the MailChimp API server. This means that you can use jQuery animations to fade out the form, display an animated spinner while the user waits, and then fade in the message. With jQuery, and a little imagination, the possibilities are endless.

The PHP files are “hidden” in the background where the user never sees them yet the jQuery ajax can still access them invisibly. Even when your website is static HTML, without any PHP, this solution will work so that nobody will ever know PHP is being used in the background.

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 form using jQuery ajax

NOTE: This posting was originally written for MailChimp API version 1 and MailChimp will stop support for API versions 1 & 2 at the end of 2016.

UPDATE:  Click HERE to view the updated solution using MailChimp API v3.0

——

I created a simple HTML page for a dynamic MailChimp sign-up form using jQuery ajax. This means that your users can signup for your MailChimp list without leaving your page. Better than that, they will signup without a page refresh, as the jQuery and `ajax()` will dynamically update the page with the response from the MailChimp API server. This means that you can use jQuery animations to fade out the form, display an animated spinner while the user waits, and then fade in the message. With jQuery, and a little imagination, the possibilities are endless.

The PHP files are “hidden” in the background where the user never sees them yet the jQuery ajax can still access them invisibly. Even when your website is static HTML, without any PHP, this solution will work so that nobody will ever see a `.php` in their URL.

1) Download the PHP 5 jQuery example here…

apidocs.mailchimp.com/downloads/mcapi-simple-subscribe-jquery.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 collect the user’s first & last name and/or other form information. You’ll 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 Variables
    	$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 what my `index.html` file looks like. This code is contained between the `<body></body>` tags:

<form id="signup" action="index.html" method="get">
        <input type="hidden" name="ajax" value="true" />
        First Name: <input type="text" name="fname" />
        Last Name: <input type="text" name="lname" />
        email Address (required): <input type="text" name="email" />
        HTML: <input type="radio" name="emailtype" value="html" checked="checked" />
        Text: <input type="radio" name="emailtype" value="text" />
        <input type="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). Place it in the same directory as your `store-address.php` file or you must update the url path within `store-address.php` file to find it.