Subscribe list users to a MailChimp mailing list using Flash
Tuesday, January 13th, 2009UPDATE:
While this code is still functional and useful for AS 2.0 projects, an updated MailChimp AS 3.0 sample is now available from kohactive!
Here’s some sample code you can use to connect your Flash signup form to the MailChimp API. I recently had a client with an existing MailChimp account ask to allow users to sign up for their newsletter through their website, which has a full Flash interface. Unfortunately I was not able to find much documentation out there about how to make this work, and it took me some hair pulling to get it sorted out. Finally, with the help of Jesse Peterson and the API team at MailChimp, we were able to get a working version that doesn’t require any additional PHP or other backend scripting. Here’s the AS:
// Edit your MailChimp specifics here.
// You shouldn't have to edit anything but these two variables
// unless you are collecting additional data.
_global.apiKey = "YOUR_MAILCHIMP_API_KEY";
_global.listID = "YOUR_MAILCHIMP_LIST_ID";
// set tab order for form usability
firstName_txt.tabIndex = 1;
lastName_txt.tabIndex = 2;
email_txt.tabIndex = 3;
submit_mc.tabIndex = 4;
// submission
submit_mc.onRelease = function()
{
// show a loading message in case transmission is slow
response_txt.text = "Sending…";
// gather form data
var firstName:String = firstName_txt.text;
var lastName:String = lastName_txt.text;
var email:String = email_txt.text;
// check the email address
// if it's valid…
if(validEmail(email)){
// disable the submit button while loading data
submit_mc.enabled = false;
// set up result xml
var result_xml:XML = new XML();
result_xml.ignoreWhite = true;
result_xml.onLoad = function(success){
// if the user is subscribed successfully, the result set
// will look something like
// <MCAPI type="boolean">1</MCAPI>
// so you can reset the form and display
// the confirmation message.
if(result_xml.firstChild.firstChild.toString() == "1"){
resetForm("Please check your email to confirm your subscription.");
}
// or else there was a data error,
// so you need to parse the error code.
else{
// Convert the error string from XML data to a string,
// then display it in the response text field.
var resultCode = result_xml.firstChild.childNodes[0].childNodes[0].toString();
_root.resetForm(resultCode);
}
}
// Set up a send XML object, even though we're not
// really sending anything in XML.
// All your data will be encoded in the send_url variable.
var send_xml:XML = new XML();
send_xml.ignoreWhite = true;
// Here's where your data is added.
// For additional text fields, add additional merge_vars
// array elements and append at the end.
var send_url:String = "http://api.mailchimp.com/1.1/?output=xml";
send_url += "&method=listSubscribe&apikey=" + apiKey;
send_url += "&id=" + listID + "&email_address=" + email;
send_url += "&merge_vars[FNAME]=" + firstName;
send_url += "&merge_vars[LNAME]=" + lastName;
// And here's how you send/load:
send_xml.sendAndLoad(send_url, result_xml);
}
// or else there's an issue with the email address
else{
// show the email error.
showErrors();
}
}
// validate an email address
function validEmail(inputEmail:String):Boolean
{
if (inputEmail.indexOf(" ")>0) {
return false;
}
var emailArray:Array=inputEmail.split("@");
if (emailArray.length != 2 || emailArray[0].length == 0 || emailArray[1].length ==0) {
return false;
}
var postArray:Array=emailArray[1].split(".");
if (postArray.length < 2) {
return false;
}
for (var i:Number=0; i<postArray.length; i++){
if (postArray[i].length < 1) {
return false;
}
}
var suffix=postArray[postArray.length-1];
if (suffix.length < 2 || suffix.length > 3) {
return false;
}
return true;
}
// delete all form elements and display a response message
function resetForm(pResponse){
submit_mc.enabled = true;
firstName_txt.text = "";
lastName_txt.text = "";
email_txt.text = "";
response_txt.text = pResponse;
Selection.setFocus("firstName_txt");
}
// select the email address and display an error message
function showErrors(){
Selection.setFocus("email_txt");
Selection.setSelection(0, email_txt.length);
response_txt.text = "Invalid email address.";
submit_mc.enabled = true;
}
Want to try it out? All you need to do to get it working is set up your MailChimp account and lists, then edit these variables:
_global.apiKey = "YOUR_MAILCHIMP_API_KEY";
_global.listID = "YOUR_MAILCHIMP_LIST_ID";
Then push your files online or test your SWF directly in the Flash Player (testing in a browser from your desktop may throw a Flash security error). You should be subscribing users in no time. Thanks again to the API team for working with me on this!
Tags: ActionScript 2.0, Flash, MailChimp


January 17th, 2009 at 9:56 am
I believe line 94, the for loop, should read:
for (var i:Number=0; i < postArray.length; i++) {
Other than that, tested and seems to work great. Thanks for sharing!
January 17th, 2009 at 10:10 am
Good catch, WordPress choked when I forgot to change that less than symbol. Code updated!
February 10th, 2009 at 5:19 am
Where do I find my list iD?
February 10th, 2009 at 5:28 am
Jessica, login to your MailChimp account, go to your lists and click “Unsubscribe form code” for the proper list. In the URL generated, your list ID is the “id” parameter, probably a 10-digit alpha numeric code. Further instructions are available in the sample code linked above, there’s a readme.txt file.
February 11th, 2009 at 12:31 am
Do i attach this code to the sign up button?
February 11th, 2009 at 1:13 am
No, you place this code on the main timeline, or include it as a separate AS file. Are you not able to view the sample files? I can save to a lower version of Flash and send directly to you if you’d like.
February 11th, 2009 at 4:14 am
I can view them, I just wasn’t sure where to look. I am a beginner flash designer and I volunteered to do a website for some friends and they want an input box for a newsletter signup so I searched how to do it and found you, so I was left confused on some parts, lol.
February 12th, 2009 at 9:55 pm
Fabulous, works perfectly
Thank you
April 8th, 2009 at 4:12 am
Thank you Christian, this was the perfect solution and will be a great new tool in my arsenal!
This is how I’ve used it:
http://www.makeyourhit.com
June 8th, 2009 at 6:18 am
Was looking for a flash answer to communicate between my mailchimp account and flash forms and I came across this little gem. It works great, but I am an actionscript 3.0 guy. I know a little 2.0, but not enough to take what you have here, and migrate it to 3.0. I’ve been trying all afternoon.
I’ve also been trying to pass my as 3.0 form variables (’email’) into the “simple-suscribe” examble code on MailChimp’s site, but to no avail, I can’t get it to work. I’m not a PHP programmer, but I can piece things together. I just can’t seem to get this one. right.
My AS 3.0 forms currently pass a ‘var email’ into a PHP file where it is collected and sent back to me via email ($senderEmail = $_POST['email'];)
A translation from your AS 2.0 code to AS 3.0 would certainly do the trick, but I know that I can pass the same variable my flash form to two different PHP files. I’m just stuck with passing my flash variable into MailChimp’s PHP files.
Any help or direction would be very much appreciated.
Take care,
Josh
June 8th, 2009 at 7:09 am
Josh, if I’m hearing you right it seems like there are 2 separate issues. 1 – you can’t get this to work as an AS3 piece. And 2 – you would like to be able to send your data to two different backend scripts or locations. For issue 1, do you have any code to post and specific error messages I could look at? I haven’t written this for AS 3, so I don’t have any code to share with you but I would be glad to take a look at what you have done so far and offer assistance. There are quite a few syntax and structure differences with AS 3 (using the URLLoader class to receive XML, can’t use “_global” variables, navigating through XML nodes is different, etc) so there are about a dozen or so things you might need to try but without errors or sample code I’m in the dark. For issue 2, I don’t see any reason why you couldn’t create 2 separate XML objects out of your gathered data and send them to 2 different locations. You may want to set up listeners so that the first XML send/load success triggers the second send/load. Again, without seeing your specific sample and error messages I’m kind of in the dark. Just out of curiosity, why are you using AS 3? Are you getting any major benefit over using AS 2? If not, consider dropping down to AS 2 – it seems much more intuitive to me. If you are getting some significant benefits for your project from AS 3, you must be doing some pretty complex scripting – in which case sending a couple of glorified XML requests shouldn’t be that difficult.
June 25th, 2009 at 2:58 am
do you know of issues where a list gets too big for the flash script to work with? I have a list of about 500, and the script would run and continually display “Sending …”. I tried changing the list id to one with a smaller list, and the script runs perfectly. From this I can see that the problem is with the list itself, not the script or my internet connection.
June 25th, 2009 at 3:49 am
Interesting, I have not heard of this issue but I’ll try to replicate on my own with a large list. I’ll let you know the results. In the meantime, have you tried creating an HTML sign up form and submitting signups to the same list (without using Flash)? Might give you some more insight into what’s happening, especially if you’re not getting any XML transmission errors through Flash.
June 25th, 2009 at 6:11 am
Thanks for the advice. I tried the html form and found that it wasn’t the size of the list after all. The server was bouncing back an error message, which the flash script couldn’t process. The error was that the email address was already in the system. This is an issue that will come up for some site visitors every now and them. Any idea on how to rework the AS to deal with this?
June 25th, 2009 at 7:05 am
Nipith, I just tested this out with a pre-existing email address and it performed as expected – a custom error message was displayed. In the tutorial there’s a switch statement set up to process error messages, and case: 214 corresponds to an email address that already exists in the list. The default case should be triggered if an unplanned error code is returned, and the actual error code from MailChimp should be displayed. The fact that you’re saying the default statement was never triggered (the feedback response never changed from ‘Sending…’) when you tried to submit an email address leaves me to believe there was a server transmission error when you submitted your request. I’d be glad to take a look at your files if you’d like, you can email them to me or email me a link to download. Click the contact link at the top for my email address.
June 25th, 2009 at 9:44 am
After playing around further with the flash file, I’ve been able to figure out that the script works fully when the form and the script is on the main timeline.
When the form and the script is in a movie clip, everything works except for the response text displaying server error message. This is why the response text hangs at “Sending …”.
I made the a small change to line 61 of the code, and deleted “_root.” in the front part of the line “_root.resetForm(resultCode);”. That did the trick.
Thanks for the code and the help.
July 25th, 2009 at 8:25 am
I set up my mail chimp account today, got it activated and pasted what I believe to be the correct “global.apiKey” and “global.listID” into the “subscribe_as2.as” file. I posted all the relevant files to a site, but when I tested a submission all that came up was the following: “Invalid Mailchimp API Key: YOUR_MAILCHIMP_API_KEY” I deleted the files and re-uploaded but to know avail. My apiKey is a alpha numeric, 32 characters long and I got it after following the instructions from the readme.txt in the tutorial. Do I need to wait for Mail Chimp to authorize the key, or is this more likely a programming error on my part somewhere?
July 25th, 2009 at 8:45 pm
Miguelito – it sounds like you changed the apikey in your AS file, but then did not republish the SWF. The AS file updates will not take effect unless you republish the SWF and upload that new file to the correct site. Try that and see if it works – if not, you have probably pasted the apikey in the wrong spot.
July 27th, 2009 at 5:45 am
This is a great file! However, I’m having some difficulty with it. After I send the data, it states “Sending…..” and then indicates “undefined” followed by clearing all of the data.
Any suggestions!
THANK YOU FOR SHARING THIS FILE!!!!
Phil
July 27th, 2009 at 11:30 am
Phil, I am not sure what the problem could be – perhaps you could post some code or zip up your files and email to me? I would be glad to take a look and see what the issue might be.
July 28th, 2009 at 6:55 am
Re-exported and re-uploaded the .swf, and now it’s working great, thanks for your help and thanks for all your hard work, this is exactly what I needed, thanks for sharing.
August 5th, 2009 at 9:22 am
im about to try to transition this as2 to as3, but before i do has anyone done this yet?
August 7th, 2009 at 5:38 am
Edit: Spelling error in api url!
Hey all– just doing an AS3 project, and turned this code into a proper class. Feel free to modify it (i.e. improve it) and re-post! Needs a little help on the returned error, but it does parse the success node that it returns.
To use it:
var s=new MailChimpSubscriber();
s.subscribe(’Buster’,’Bogheart’,’buster@lklk.com’);
package{
import flash.net.*;
import flash.events.Event;
public class MailChimpSubscriber{
private const apiKey:String = “yourapikey”
private const listID:String = “yourlistid”;
private var resultXml:XML;
public function MailChimpSubscriber(){
}
public function subscribe(firstName:String,lastName:String,email:String){
if (!emailValidate(email)) {
unsuccessful(’invalid email’);
return; //skips rest
}
var sendUrl:String = “http://api.mailchimp.com/1.1/?output=xml&method=listSubscribe&apikey=” + apiKey + “&id=” + listID + “&email_address=” + email + “&merge_vars[FNAME]=” + firstName + “&merge_vars[LNAME]=” + lastName;
var req:URLRequest = new URLRequest(sendUrl);
req.method = URLRequestMethod.POST;
var loader:URLLoader = new URLLoader();
loader.addEventListener(Event.COMPLETE,function(e){
resultXml=new XML(e.target.data);
if (resultXml==’1′) successful();
else unsuccessful(’Returned error’);
});
try{
loader.load(req);
}
catch (e:Error) {
unsuccessful(e.toString());
}
}
private function successful(){
//something
}
private function unsuccessful(msg:String){
trace(msg);
}
private function emailValidate(email:String):Boolean{
var emailRgx:RegExp = /^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
return emailRgx.test(email);
}
}
}
August 7th, 2009 at 6:16 am
Awesome! Thanks for sharing Ethan.
October 16th, 2009 at 1:16 am
Everything works great!
I am trying to include checkboxes that allow users to sign up for various types of emails. I am not sure what to append to the send_url string in order for Mail Chimp to know which of the list segments people want to be included in.
I tried send_url += “&merge+vars[group[1]]=1″; and other variations of this, but to no avail.
Thanks!
October 16th, 2009 at 2:22 am
I actually figured this out, so I thought I would share in case anyone else needs to do this.
For adding checkboxes that sign users up to particular segments of the list, add a variable which constructs itself based on which boxes are checked….
var interests:String = new String;
if (group1.selected == true) {
interests += “Group One Name”;
}
if (group2.selected == true) {
interests += “, Group Two Name”;
}
(of course, Group One Name would be replaced with the ACTUAL name of the group.)
Then, append this to the end of the send_url statement:
+ “&merge+vars[INTERESTS]=” + interests
October 22nd, 2009 at 5:58 am
Thank you for publishing this.
February 8th, 2010 at 11:57 pm
Im still struggling with this ;o(
Im really newb to this. I have made form fills in flash with variable
FNAME
LNAME
EMAIL
Now ive pasted the above code above changing the api as recommended. I’m still a bit vague about list ID
What does the “// set tab order for form usability” mean?
Do I have to upload some sort of html to my webpage server?
Im still at a loss
Sorry
February 9th, 2010 at 12:57 am
Alan, “set tab order for form usability” is there so that when a user enters their name in the form field, then presses the “tab” key, the cursor moves automatically to the next form field. This is a standard usability practice so that persons with limited mobility do not need to use a mouse to navigate through the form fields. You do not need any additional HTML to make this work.
It sounds like you’re naming your form fields using the “variable” field in the properties panel. Don’t do that
Instead, give your form fields instance names in the properties panel and leave the “variable” field blank. I hope this helps!
February 10th, 2010 at 1:48 am
Thanks for the reply.
I won’t keep writing cos I don’t want to fill up your blog with my rubbish!
So in my flash file I make some text entry fields using the text tool with ‘input text’ option selected, I give them instance names FNAME, LNAME and EMAIL. I then create a button from the common libraries.
I make sure no specific item is selected then open the action window and paste the above code in. i change the apicode string to a little 10 digit number something like this ‘123abcde [edited by admin]‘ and list id to something that looks like this ‘QWERTYPOIUt [edited by admin]‘. Then that should be it?
Do I somehow have to link the button, or the fields or something? I think the button is where my problem is, cos its not doing anything when i click it and there is nothing in the action.
Maybe I am missing a huge step-cos there is no form thing in my library etc. Oh dear
Sorry, I am a true amateur, who has been struggling to build my site for my music on no knowledge. It has been a real struggle and this is the last hurdle if you like. I am very grateful for your help!
A
February 10th, 2010 at 2:03 am
No problem Alan, I’m going to email you directly and see if we can get it working for ya!
February 10th, 2010 at 2:38 am
Thanks!
Sorted!
Excellent help ;o)
February 28th, 2010 at 2:03 am
Thanks, this was really helpful.
Now, do you happen to have a “share with a friend” mailchimp form for Flash?
March 1st, 2010 at 10:07 am
Hi Artemis, glad to be of help. Not sure I understand how the “share with a friend” mailchimp form would work – how would it tie in to MailChimp? A “share with a friend” form might be helpful on your site, but I don’t see how it would need to integrate with MailChimp in any way. If a simple mail form is sufficient, you might check out this tutorial.
May 7th, 2010 at 2:38 am
Hello Christian. Great work on this form. I do have a strange issue. I integrated all of your pieces into my existing Flash stuff and it all seems to work. I get a successful message when testing online. However, I never receive the confirmation email, nor does the Mail Chimp List show a new subscriber. Any thoughts? The API Key and List are both brand new…maybe a delay on Mail Chimp’s side or did I miss adding a variable to the .as file?
May 7th, 2010 at 2:54 am
That is interesting – is it possible the confirmation message is going into your spam folder, or is it possible your email server is experiencing issues? What if you try subscribing a different email?
August 19th, 2010 at 12:23 am
We have been looking for this of code for some time. I have sent it over to my developer and will let you know how it works for us. Thanks so much!
August 20th, 2010 at 2:21 am
Hi Christian, thanks for sharing this to us. I was wondering if it´s possible to add a field for my users brithday using the Date field of Mailchimp.
Thanks a lot.
August 20th, 2010 at 3:06 am
Hi Chema, you’re welcome! Always pleased to know that something I’ve worked on is useful to others. It is possible to add a field for your user’s birthday and pass that to MailChimp. How do you plan to collect that information? I would imagine you can create a text input area where the user can type it in, or you can create a series of dropdown fields where the user can select a day, month and year. Then you will need to write a validation script that ensures this data is both valid (for instance, they have not tried to enter February 40, 109) and formatted correctly (YYYY-MM-DD is MailChimp’s preferred format). If not, you need to present an error message to the user describing the problem and prompting them to correct it. When the data is both valid and formatted correctly, you would need to append that information in to the send_url variable. How you add that information depends on the name you have given to the “date” field in your mailing list and the variable name you are using to store that string data – for instance a mailing list field named “USERBDAY” and a string named “bDayString” would be added as “&merge_vars[USERBDAY]=” + bDayString. Not sure how familiar you are with Flash development, so this is a very high-level overview of the steps you would need to take. If you need more specific information, feel free to post here and I will try to help you out!