public
Last active

Subscribing to a Campaign Monitor list using AJAX

  • Download Gist
ajaxsubscribe.html
HTML
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
<!-- 1. Take your Campaign Monitor subscribe form as generated through the app: -->
 
<form action="http://jamesd.createsend.com/t/r/s/aljhk/" method="post" id="subForm">
<div>
<label for="name">Name:</label><br /><input type="text" name="cm-name" id="name" /><br />
<label for="aljhk-aljhk">Email:</label><br /><input type="text" name="cm-aljhk-aljhk" id="aljhk-aljhk" /><br />
<input type="submit" value="Subscribe" />
</div>
</form>
 
<!-- 2. Add some JavaScript -->
 
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$('#subForm').submit(function (e) {
e.preventDefault();
$.getJSON(
this.action + "?callback=?",
$(this).serialize(),
function (data) {
if (data.Status === 400) {
alert("Error: " + data.Message);
} else { // 200
alert("Success: " + data.Message);
}
});
});
});
</script>
 
<!-- 3. AJAX subscription to your list! -->

This is enabled by JSONP callbacks. We allow the name of a callback function to be specified in the query string (which is only allowed to contain alphanumeric characters and underscores):

http://myaccount.createsend.com/t/r/s/aljhk/?callback=my_callback

Which will return you a result as JSON, padding with a function named by your callback value. Something like:

my_callback({
  "Status": 400,
  "Message": "Sorry, but the email address you supplied was invalid and needs to be fixed before you can subscribe to this list.",
  "RedirectUrl": null
})

The resulting JavaScript object has three fields:

Status: A number representing the subscription status. 200 if subscription was successful, or 400 if subscription was unsuccessful.
Message: A string containing a message which describes the subscription status.
RedirecUrl: A string containing a redirect URL, only if subscription is successful and you have set up a redirect URL for the list in your account, otherwise null.

These are the possible values for the Message field (as of the time of writing, but subject to potentially changing):

When Status is 200 (Success Messages)

  • Your subscription has been confirmed. You've been added to our list and will hear from us soon.
  • You've just been sent an email to confirm your email address. Please click on the link in this email to confirm your subscription.

The difference between these two messages is determined by whether or not your list is a double opt-in, so you can display whatever message you prefer.

When Status is 400 (Failure Messages)

  • Invalid callback. Callback value may only contain alphanumeric characters and underscores.
  • This subscribe form requires that you fill in a CAPTCHA to be added to the list.
  • Sorry, but the email address you supplied was invalid and needs to be fixed before you can subscribe to this list.

The error conditions causing the first two failure messages should be discovered during form setup and testing, so once the form is setup and operating the only real reason for failure is an invalid email address.

Hrmm, this looks awesome, but seems to be erroring out a bit for me.
I get “Message: "Sorry, but the email address you supplied was invalid and needs to be fixed before you can subscribe to this list."” on every submission. :/

Does your form work successfully without the additional js (i.e. in a non-ajax way)? If you can point me to where the form is, I can take a look...

Hey! Thanks so much for the response! :)

Does your form work successfully without the additional js (i.e. in a non-ajax way)?

Yeah, sure does, works just fine.

If you can point me to where the form is, I can take a look...

Sorry the code is not live currently, but I have copied the relevant sections into a gist if that helps?
I dont think I'm doing anything unlike the example from the announcement post, but I just cannot seem to get it behaving as expected.

Cheers mate, thanks,

Justin

On 05/09/2011, at 1:11 PM, jdennes wrote:

Does your form work successfully without the additional js (i.e. in a non-ajax way)? If you can point me to where the form is, I can take a look...

Reply to this email directly or view it on GitHub:
https://gist.github.com/1155479

I emailed you the test I used to test this in your account (js only - no Coffeescript). Hope that helps.

Hi,

How can i add the functionality so that it requires the name field to be filled?

Thanks in advance,
Sam

Hey Sam, we don't offer an option to enforce that server-side, but you can easily achieve it client-side. We have a blog post detailing how to do this using the jQuery validate plugin.

I'm not able to get additional mailing-list checkboxes to submit when using this AJAX script. I've tested the serialized string and that contains all the information and the name and email address are added to the default mailing list, but no records are adding to the additional mailing-lists. I was also having the same problem with custom fields initially so I chose the multiple list option instead.

It works fine without jquery, but with jquery I only seem to get the basic name/email data?

Any assistance would be greatly appreciated.

You can see the existing form here www.barmade.co.uk

Hey Luke, I've fixed an issue which was causing some issues with that, so you shouldn't have a problem with that now. Let us know if you do.

Hi,

The default code broke when using mootools, thought I might share what I came up with if anyone else is interested. The default behaviour of the Mootools JSONP class creates a callback function with a "." character in its name, as this is forbidden (cf first comment in this thread "which is only allowed to contain alphanumeric characters and underscores"), it is necessary to override this default behavior and use a custom function as the callback.

      window.mySubFormCallBack = function(data)
      {
        if (data.Status === 400) {
            alert("Error: " + data.Message);
        } else { // 200
            alert("Succes: " + data.Message);
        }
      }

      $('subForm').addEvent('submit',function (e) {
          e.stop();
          new Request.JSONP(
            {
              url:this.action,
              callbackKey: "override"
            }).send("callback=mySubFormCallBack&"+this.toQueryString()+"&_="+Math.random());
          return false;
      });  

Hi,

If an active subscriber of a double opt-in list subscribes again through the AJAX form, the success message is still displayed and tells him he will receive a confirmation email, which is never sent by the system. How to display a specific message (already a subscriber) in this case?

Franck

Works like a charm, thanks!

Hi franckmartin,

I'm afraid the form submission endpoint just doesn't provide that kind of information. If you're looking to distinguish between those cases, you'll need to incorporate the API and check the subscriber's state before attempting to add them to the list.

Hi,

How can I incorporate the JSON call with the following jQuery from a SimpleModal window?

                    function () {
                        $('#contact-container .contact-loading').fadeIn(200, function () {
                            $.ajax({
                                url: 'http://***.createsend.com/t/j/s/ihjtl/',
                                data: $('#contact-container form').serialize() + '&action=send',
                                type: 'post',
                                cache: false,
                                dataType: 'html',
                                success: function (data) {
                                    $('#contact-container .contact-loading').fadeOut(200, function () {
                                        $('#contact-container .contact-title').html('Thank you!');
                                        msg.html(data).fadeIn(200);
                                    });
                                },
                                error: contact.error
                            });
                        });

banging my head a bit - every submission comes back with invalid email error - including valid email addresses that are not on the list - using a double-opt-in if that makes any difference, but it's the same if I set it to single-opt-in

Is this service still up and working as described?
I get a "Error: This subscribe form requires that you fill in a CAPTCHA to be added to the list."

Alternative, to use jQuery's built in support for JSONP, to avoid having to manually append the callback parameter to the URL: https://gist.github.com/mkdynamic/5754791

Not tested, code might need syntax tweaks.

Seems like this doesn't work for the unsubscribe form? All I get back is html even with the same jsonp call as above :( It would be awesome if they did add support for it!

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.