Skip to content

Instantly share code, notes, and snippets.

@superstrong
Last active March 11, 2016 03:28
Show Gist options
  • Save superstrong/c87a71028997af0cd679 to your computer and use it in GitHub Desktop.
Save superstrong/c87a71028997af0cd679 to your computer and use it in GitHub Desktop.
Add proper Segment tracking to your Mailchimp signup form
userId is a better way to join data at the user level across various tracking/email/etc. services. Why?
- UserId is stable (e.g., update a user's email address from anywhere by calling Segment identify with the same userId.)
- UserId is not PII (e.g., Google Analytics explicitly forbids using PII as a userId)
So, in addition to manually adding a subscriber to your Mailchimp list, this will explicitly assign a userId to each new subscriber and identify the user via Segment.
Quick steps:
- Get your Mailchimp list embed code here: Lists -> {list} -> Signup forms -> Embedded forms
- Use it to replace the three values in the "action" line below with your own. Also change "us6" if yours is different.
- In the hidden input field with id "bot-field", replace the name with the one from your own embed code.
- To add or remove form fields, mofiy the form HTML and related code in the "callSegment" function.
Built on @rydama's "mailchimp-ajax-signup" JS to submit form without redirects: https://github.com/rydama/mailchimp-ajax-signup
###
<form id="subscribe-form" action="http://<your_account>.us6.list-manage.com/subscribe/post-json?u=<your value>&id=<your value>" method="get">
<h3>Want more great content delivered to your inbox?</h3>
<p>(no spam ever, unsubscribe at any time)</p>
<div>
<input type="text" placeholder="first name" value="" id="mce-FNAME" name="FNAME">
<input type="text" placeholder="last name" value="" id="mce-LNAME" name="LNAME">
<input type="email" placeholder="email *" value="" id="mce-EMAIL" name="EMAIL">
</div>
<!-- Do not remove this or risk form bot signups -->
<div style="position: absolute; left: -5000px;" aria-hidden="true">
<input type="text" id="bot-field" name="<your name here>" tabindex="-1" value="">
</div>
<div class="clear">
<input type="submit" value="Keep Me Updated" id="mc-embedded-subscribe" class="btn btn-large" name="subscribe">
</div>
<!-- The subsription response message will be inserted below -->
<div id="subscribe-result"></div>
</form>
[jQuery]
[Your Segment analytics.js]
<script type="text/javascript">
$(document).ready(function(){
ajaxMailChimpForm($("#subscribe-form"), $("#subscribe-result"));
// Turn the given MailChimp form into an ajax version of it.
function ajaxMailChimpForm($form, $resultElement){
// Hijack the submission. We'll submit the form manually.
$form.submit(function(e) {
e.preventDefault();
if (!isValidEmail($form)) {
var error = "A valid email address must be provided.";
$resultElement.html(error);
$resultElement.css("color", "red");
} else {
$resultElement.css("color", "black");
$resultElement.html("Subscribing...");
submitSubscribeForm($form, $resultElement);
}
});
}
// Validate the email address in the form.
function isValidEmail($form) {
// If email is empty, show error message.
// contains just one @
var email = $form.find("input[type='email']").val();
if (!email || !email.length) {
return false;
} else if (email.indexOf("@") === -1) {
return false;
}
return true;
}
// Submit the form with an ajax/jsonp request.
// Based on http://stackoverflow.com/a/15120409/215821
function submitSubscribeForm($form, $resultElement) {
$.ajax({
type: "GET",
url: $form.attr("action"),
data: $form.serialize(),
cache: false,
dataType: "jsonp",
jsonp: "c", // Trigger MailChimp to return a JSONP response.
contentType: "application/json; charset=utf-8",
error: function(error){
// According to jquery docs, this is never called for cross-domain JSONP requests.
},
success: function(data){
if (data.result !== "success") {
var message = data.msg || "Sorry. Unable to subscribe. Please try again later.";
$resultElement.css("color", "red");
if (data.msg && data.msg.indexOf("already subscribed") >= 0) {
message = "You're already subscribed. Thank you.";
$resultElement.css("color", "black");
callSegment();
}
$resultElement.html(message);
} else {
$resultElement.css("color", "black");
$resultElement.html("Thank you!<br>You must confirm the subscription in your inbox.");
callSegment();
}
}
});
}
});
// Run the submission data through Segment.
function callSegment() {
var bot = document.getElementById('bot-field').value;
if(bot.length>0) {
// If a bot it submitting the form, stop now.
return false;
} else {
// Get userId from Segment cookie if it exists. If it doesn't, generate a UUID.
var segmentId = analytics.user().id();
var anonymousId = analytics.user().anonymousId();
if (segmentId === null) {
var userid = anonymousId;
} else {
var userid = segmentId;
}
var email = document.getElementById('mce-EMAIL').value;
var firstname = document.getElementById('mce-FNAME').value;
var lastname = document.getElementById('mce-LNAME').value;
// Make the calls
analytics.identify(userid, {
firstname: firstname,
lastname: lastname,
email: email
});
analytics.track('Subscribed', {
source: 'Mailchimp Form'
});
return false;
}
};
</script>
@superstrong
Copy link
Author

This is now a proper repo: Mailchimp-Ajax-Segment

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment