Scroll to top
buildasubscribeformusingphpjavascriptandmailchimpapi
Go to Blog Page Published / May 13, 2021

Build a subscribe form using PHP, JavaScript, and Mailchimp API.

Build a subscribe form using PHP, JavaScript, and Mailchimp API.

All website owners demand to have a subscribe form on their website due to “marketing reasons” and we as developers have to code that feature for them. Most popular around is Mailchimp Signup Forms. Mailchimp already offers an Integration facility to connect one’s Mailchimp account to the apps and tools they already use. Which helps in making marketing easier.

Besides Mailchimp Integrations, Mailchimp also offers Embedded Signup Forms, which are mostly used to create the signup forms. It goes fine, but it becomes so much complicated to customize the form if you are responsible to add custom looks to it. You just continue adding unnecessary HTML and CSS. 😫

In this article, we will keep that additional customization of Embedded Forms alone and would focus on building a subscribe form right from scratch using Mailchimp Marketing API. I promise you, It’s so easy and precise, you would never look back for Embedded Signup Forms. Let’s dive right into it.

Mailchimp Marketing API helps manage audiences, integrate your data, and send timely, relevant email campaigns. We are particularly interested in managing our audiences i.e we need to add contacts (in our case user emails only) to our Audience list.

Prerequisites

API Key

Navigate to the API Keys section of your Mailchimp account. If you already have an API key listed and you’d like to use it for your application, simply copy it. Otherwise, click Create a Key and give it a descriptive name that will remind you which application it’s used for.

Server Prefix

Log into your Mailchimp account and look at the URL in your browser. You’ll see something like https://us4.admin.mailchimp.com/ the us4 part is the server prefix.

Note that your specific value of Server Prefix may be different.

We have our prerequisites in place. Now we can focus on the coding part.

I would be specifically coding in PHP, whereas Mailchimp Marketing API is also available for Node.jsPython & Ruby. Feel free to choose your language.

I have already created a boilerplate for the subscribe form that we will be working on. You can download it on this Github Repo and add it to your local server (localhost).

Open the project directory subscribe-form-mailchimp in your preferred code editor and you would have the following directory structure.

subscribe-form-mailchimp
 |- .gitignore
 |- composer.json
 |- index.php
 |- normalize.css
 |- script.js
 |- subscribe.php

Install Client Library

I have already added composer.json file to the project with mailchimp/marketing as the required package. To install this package open your terminal (make sure you are in the project directory) and run composer update which will install the required packages inside the vendor directory.

Let’s Code

To test that you have everything set up correctly, we’ll make a simple request to the ping endpoint. Hitting this endpoint acts as a health check on the Mailchimp API service.

Open subscribe.php file and add following lines of code to it.

require_once 'vendor/autoload.php';

$mailchimp = new \MailchimpMarketing\ApiClient();
 
$mailchimp->setConfig([
	'apiKey' => 'YOUR_API_KEY', // Replace this with your API Key
	'server' => 'YOUR_SERVER_PREFIX' // Replace this with your Server Prefix
]);

$response = $mailchimp->ping->get();
print_r($response);

If everything was set up correctly and the request was a success, the response should look like the snippet below. (open subscribe.phphttp://localhost/subscribe-form-mailchimp/subscribe.php)

stdClass Object ( [health_status] => Everything's Chimpy! )

Now that we’re successfully making authenticated requests to the API with your API Key and PHP client library, we’re ready to dive into the Mailchimp Marketing API for adding contacts (emails) to our subscriber’s list. Before that, we need list_id of our Audience.

To get the list_id follow below steps:

  • Click the Audience icon on the navigation bar present on the left side of the page.
  • On the Audience page, click the Manage Audience dropdown placed on the right side of your screen.
  • Click on Settings.
  • Scroll to the very bottom of the page and you will see audience list_id.
  • Copy it, and we will use it in the next step.

We got the Audience List ID in the previous step, now update the subscribe.php file with the following code (replace the previous code with this one).

require_once 'vendor/autoload.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  // Sanitizing Email Input
  $email = strtolower(filter_var($_POST['email'], FILTER_SANITIZE_STRING));

  // Check Email Entry
  if (empty($email)) {
    http_response_code(400);
    $response = [
      'status' => 'error',
      'message' => 'email address is mandatory.',
    ];
    echo json_encode($response);
    exit();
  }

  // Validating Email
  if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    http_response_code(400);
    $response = [
      'status' => 'error',
      'message' => 'invalid email address.',
    ];
    echo json_encode($response);
    exit();
  }

  // Mailchimp Marketing API Instance
  $mailchimp = new \MailchimpMarketing\ApiClient();

  // API Key & Server Prefix
  $mailchimp->setConfig([
    'apiKey' => 'YOUR_API_KEY', // Replace this with your API Key
    'server' => 'YOUR_SERVER_PREFIX' // Replace this with your Server Prefix
  ]);

  // Auidence List ID
  $list_id = 'YOUR_LIST_ID'; // Replace this with your List ID

  // subscriber_hash is the MD5 hash of the lowercase email
  $subscriber_hash = md5($email);

  try {
    $contact = $mailchimp->lists->setListMember($list_id, $subscriber_hash, [
      'email_address' => $email,
      'status' => 'subscribed',
    ]);

    if (is_object($contact) && $contact->email_address == $email) {
      http_response_code(200);
      $response = [
        'status' => 'success',
        'message' => 'Great! You are subscribed successfully.',
      ];
      echo json_encode($response);
      exit();
    }
  } catch (Exception $e) {
    http_response_code(400);
    $response = [
      'status' => 'error',
      'message' => 'Sorry! Please enter another email.',
    ];
    echo json_encode($response);
    exit();
  }
} else {
  http_response_code(403);
  echo 'Page access not allowed.';
  exit();
}

Now let’s add some JavaScript in script.js file so that we can pass the user input (email address in this case) to subscribe.php file and it would then validate and process it accordingly.

'use strict';

const subscribeForm = document.querySelector('.subscribe__form');
const alertBox = document.querySelector('.alert');

subscribeForm.addEventListener('submit', e => {
  e.preventDefault();

  const formData = new FormData(subscribeForm);

  const xhr = new XMLHttpRequest();
  xhr.open('POST', 'subscribe.php');
  xhr.responseType = 'json';
  xhr.send(formData);
  xhr.onload = () => {
    switch (xhr.status) {
      case 200:
        alertBox.style.display = 'inline-block';
        alertBox.classList.remove('alert--error');
        alertBox.classList.add('alert--success');
        alertBox.innerHTML = xhr.response.message;
        subscribeForm.reset();
        setTimeout(() => {
          alertBox.style.display = 'none';
        }, 3000);
        break;

      case 400:
        alertBox.style.display = 'inline-block';
        alertBox.classList.remove('alert--success');
        alertBox.classList.add('alert--error');
        alertBox.innerHTML = xhr.response.message;
        break;

      default:
        console.log(`ERROR:: ${xhr.status}, ${xhr.statusText}`);
        break;
    }
  };
});

Now with all the code in place, got to the index page, reload and try it out. Enter wrong emails, input the right ones, and the valid email addresses will get added to your Mailchimp account.

Subscribe Form Live Preview 🎁

Also, you see how clean our code is, we have no unnecessary CSS overrides, no third-party Javascript or jQuery. It’s simple, clean, and to the point. Hope you managed to get all the chunks right. If anything in this article is taking you for a ride, feel free to drop a comment below.

If you loved to read this article and gained value from it, please like, share, and do subscribe below so that you can get my latest articles right into your inbox once a month. ✌️