Building a Subscription form with PHP and the Mailchimp 3.0 API

Recently I built a Landing Page and wanted to implement a newsletter subscription form integrated with Mailchimp. Most of the tutorials I found online were for older versions of the Mailchimp API or for specific platforms like WordPress so I decided to write this post explaining how I implemented it using PHP and jQuery.

The Easy Part – HTML

Start by pasting this code where you want to place the newsletter form:

<h4 class="widget_title">Subscribe to the Newsletter</h4> 
<p id="newsletter_message">Receive our weekly news on your email.</p> 

<form class="mailchimp_form" method="POST" action="mailchimp.php"> 
  <div class="input-group"> 
    <input type="email" id="email" name="email" class="form-control" placeholder="Enter your e-mail here" required/> 
    <input type="text" value="pending" id="status" name="status" hidden/>
    <input type="submit" class="newsletter_submit" value="Submit"> 
  </div> 
</form>

You will also need to include a Javascript file with the script to process the subscription form data without the need to reload the page, so place the following code before your </head> tag:

<script src="http://code.jquery.com/ui/1.12.0/jquery-ui.js"></script><script src="mailchimp.js"></script>

The Hard Part – PHP

Now you will have to configure a new email list and have an active mailchimp API key.

To create a list go to mailchimp.com, login and click on the menu item Lists. Then click on the top-right button “Create List”, complete all the details and go to List Settings > List names and defaults page and grab the list ID.

screen-shot-2016-09-11-at-21-45-24

To generate an API key go to Username > Account > Extras > API Keys and generate one. Save the API key as well.

Additionally you need to know the server Mailchimp is using to host your list. To know this, look at the address bar when you are inside your Mailchimp account. The url should be usx, being x a number, followed by admin.mailchimp.com.

screen-shot-2016-09-11-at-21-48-10

Now create a file called mailchimp.php, paste the following code inside and fill in the details you got before:

<?php

// Owner Information
$api_key = '96ddff4f3d7c070ba2e0678f2247f5a2';
$datacenter = 'us4';
$list_id = 'cb01456127';
$username = 'userexample';

// Subscriber Information
$email = $_POST['email'];
// Connection Data
$url = 'https://'. $datacenter .'.api.mailchimp.com/3.0/lists/'. $list_id .'/members/';
$data = array("email_address" => $email,"status" => "pending");
$data_string = json_encode($data);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, "$username:$api_key");
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
 'Content-Type: application/json',
 'Content-Length: ' . strlen($data_string))
);

$result=curl_exec ($ch);
curl_close ($ch);

echo $result;
?>

The magic – jQuery

Now that we have the form in place on the page and the code to connect to the mailchimp servers we have to process the data from the form and submit it, ideally without having to reload the page.

To do so create a file called mailchimp.js and paste the following code inside:

$('document').ready(function(){
 $('.mailchimp_form').submit(function(e){

 // Prevent the form from being submitted via the browser directly
 e.preventDefault();

 // Grabs the attributes and values from the form
 var data = {email: $('#email').val()};
 var endpoint = $(this).attr('action');

 // Makes the ajax request
 $.ajax({
 method: 'POST',
 dataType: "json",
 url: endpoint,
 data: data
 }).success(function(data){

if(data.id){

 // Clean Previous Data and Success Message
 $("p#newsletter_message").empty();
 $("p#newsletter_message").append('Thanks for signing up.');

} else if (data.title == 'Member Exists') {

 // Clean Previous Data and Error Message
 $("p#newsletter_message").empty();
 $("p#newsletter_message").append('Thanks, but you are alredy signed up.');

} else {

 // Clean Previous Data and Error Message
 $("p#newsletter_message").empty();
 $("p#newsletter_message").append('Sorry but there is something wrong. Please try later.');

}

}).error(function(){

 // Clean Previous Data and Server Issue Message
 $("p#newsletter_message").empty();
 $("p#newsletter_message").append('Sorry but there is something wrong. Please try later.');

});

});
});

As you can see we process the request using Ajax and display different messages depending on the outcome of our request. These messages are displayed on the paragraph we have above the newsletter form.

Here is how my subscription form looks like:

form

I hope that this post was useful to you! Please let me know in the comments if you have any doubt.

Leave a Reply

Your email address will not be published. Required fields are marked *