Create a Basic Mailchimp Signup Form Using Their API

Create a basic MailChimp signup form using their API

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!  Check your inbox or spam folder for a message containing a confirmation link.';
} else {
// An error ocurred, return error message
return '<b>Error:</b>  ' . $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.

AJAX Mailchimp signup form integration

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...
}
}
});
}

How to create new mailing list using Mailchimp API v.3 and get its id?

Using PHP and cURL:

<?php

$apikey = '<api-key>'; // replace with your API key
$dc = '<data-center>'; // replace with your data center

$data = array( // the information for your new list--not all is required
"name" => $name,
"contact" => array (
"company" => $company,
"address1" => $address1,
"address2 => $address2,
"city" => $city,
"state" => $state,
"zip" => $zip,
"country" => $country,
"phone" => $phone
),
"permission_reminder" => $permission_reminder,
"use_archive_bar" => $archive_bars,
"campaign_defaults" => array(
"from_name" => $from_name,
"from_email" => $from_email,
"subject" => $subject,
"language" => $language
),
"notify_on_subscribe" => $notify_subs,
"notify_on_unsubscribe" => $notify_unsubs,
"email_type_option" => $type,
"visibility" => $visibility
);
$data = json_encode($data); // API requires JSON objects
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://".$dc.".api.mailchimp.com/3.0/lists/"); // ../lists/ URL to create new list resource
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTREQUEST, true); // declare request is POST type
curl_setopt($ch, CURLOPT_POSTFIELDS, $data); // set POST data
curl_setopt($ch, CURLOPT_USERPWD, "user:".$apikey); // HTML Basic Auth
$output = curl_exec($ch); // execute and capture response
curl_close($ch);
print_r($output); // display API response

?>

For a neat way to get a feel for the API, I highly recommend playing around in the MailChimp API Playground.



Related Topics



Leave a reply



Submit