Create a gist now

Instantly share code, notes, and snippets.

@jdennes /LICENSE
Last active Apr 21, 2018

What would you like to do?
Subscribing to a Campaign Monitor list using AJAX
<!-- 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! -->
@jdennes

This comment has been minimized.

Show comment Hide comment
@jdennes

jdennes Aug 18, 2011

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.

Owner

jdennes commented Aug 18, 2011

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.

@plasticine

This comment has been minimized.

Show comment Hide comment
@plasticine

plasticine Sep 5, 2011

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. :/

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. :/

@jdennes

This comment has been minimized.

Show comment Hide comment
@jdennes

jdennes Sep 5, 2011

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...

Owner

jdennes commented Sep 5, 2011

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...

@plasticine

This comment has been minimized.

Show comment Hide comment
@plasticine

plasticine Sep 5, 2011

@jdennes

This comment has been minimized.

Show comment Hide comment
@jdennes

jdennes Sep 5, 2011

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

Owner

jdennes commented Sep 5, 2011

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

@SamHembury

This comment has been minimized.

Show comment Hide comment
@SamHembury

SamHembury Sep 5, 2011

Hi,

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

Thanks in advance,
Sam

Hi,

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

Thanks in advance,
Sam

@jdennes

This comment has been minimized.

Show comment Hide comment
@jdennes

jdennes Sep 5, 2011

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.

Owner

jdennes commented Sep 5, 2011

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.

@lukesturgeon

This comment has been minimized.

Show comment Hide comment
@lukesturgeon

lukesturgeon Sep 6, 2011

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

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

@jdennes

This comment has been minimized.

Show comment Hide comment
@jdennes

jdennes Sep 7, 2011

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.

Owner

jdennes commented Sep 7, 2011

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.

@poudro

This comment has been minimized.

Show comment Hide comment
@poudro

poudro Oct 8, 2011

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;
      });  

poudro commented Oct 8, 2011

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;
      });  
@franckmartin

This comment has been minimized.

Show comment Hide comment
@franckmartin

franckmartin Nov 16, 2011

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

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

@heartcode

This comment has been minimized.

Show comment Hide comment
@heartcode

heartcode Jan 31, 2012

Works like a charm, thanks!

Works like a charm, thanks!

@itgoeslikethis

This comment has been minimized.

Show comment Hide comment
@itgoeslikethis

itgoeslikethis Feb 23, 2012

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 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.

@moniarde

This comment has been minimized.

Show comment Hide comment
@moniarde

moniarde Mar 2, 2012

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
                            });
                        });

moniarde commented Mar 2, 2012

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
                            });
                        });
@nubz

This comment has been minimized.

Show comment Hide comment
@nubz

nubz Sep 14, 2012

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

nubz commented Sep 14, 2012

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

@funkyboy

This comment has been minimized.

Show comment Hide comment
@funkyboy

funkyboy May 7, 2013

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."

funkyboy commented May 7, 2013

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."

@mkdynamic

This comment has been minimized.

Show comment Hide comment
@mkdynamic

mkdynamic Jun 11, 2013

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.

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.

@jordxn

This comment has been minimized.

Show comment Hide comment
@jordxn

jordxn Nov 29, 2013

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!

jordxn commented Nov 29, 2013

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!

@elmalto

This comment has been minimized.

Show comment Hide comment
@elmalto

elmalto Jan 27, 2016

for angular, short snippet:

change YOUR_URL to the action url and EMAIL_FIELD_NAME to your email field name. Other fields accordingly

    $scope.addSubscription = function (email) {

          var url = 'YOUR_URL?callback=JSON_CALLBACK&EMAIL_FIELD_NAME=' + email;

          $http.jsonp(url).then(
            function (response) {
              if (response.data && response.data.Status === 400) {
                // process error
              }
              else if (response.data  && response.data.Status === 200) {
              // process success
              }
            },
            function (error) {
              // process failure
              console.error('Signup Error: %o', error);
            }
          );
        };

elmalto commented Jan 27, 2016

for angular, short snippet:

change YOUR_URL to the action url and EMAIL_FIELD_NAME to your email field name. Other fields accordingly

    $scope.addSubscription = function (email) {

          var url = 'YOUR_URL?callback=JSON_CALLBACK&EMAIL_FIELD_NAME=' + email;

          $http.jsonp(url).then(
            function (response) {
              if (response.data && response.data.Status === 400) {
                // process error
              }
              else if (response.data  && response.data.Status === 200) {
              // process success
              }
            },
            function (error) {
              // process failure
              console.error('Signup Error: %o', error);
            }
          );
        };
@llos

This comment has been minimized.

Show comment Hide comment
@llos

llos Mar 18, 2016

I have SSL in my website and I can't use this code because of this error:

jquery.js?ver=1.11.3:5 Mixed Content: The page at 'https://www.../' was loaded over HTTPS, but requested an insecure script 'http://newsletter.....com/t/t/s/blleu/?callback=jQuery1113014936348…726137_1458306406869&cm-blleu-blleu=...'. This request has been blocked; the content must be served over HTTPS.

Any ideas of how can I use it over HTTPS?

Thanks

llos commented Mar 18, 2016

I have SSL in my website and I can't use this code because of this error:

jquery.js?ver=1.11.3:5 Mixed Content: The page at 'https://www.../' was loaded over HTTPS, but requested an insecure script 'http://newsletter.....com/t/t/s/blleu/?callback=jQuery1113014936348…726137_1458306406869&cm-blleu-blleu=...'. This request has been blocked; the content must be served over HTTPS.

Any ideas of how can I use it over HTTPS?

Thanks

@petsto

This comment has been minimized.

Show comment Hide comment
@petsto

petsto Mar 31, 2016

Works like a charm! Thank you!

petsto commented Mar 31, 2016

Works like a charm! Thank you!

@sebszocinski

This comment has been minimized.

Show comment Hide comment
@sebszocinski

sebszocinski Aug 15, 2016

Hi, I'm not getting any errors saying the email has already subscribed (already in the list) it just keeps giving me a success message. I think this would be a nice feature.

Hi, I'm not getting any errors saying the email has already subscribed (already in the list) it just keeps giving me a success message. I think this would be a nice feature.

@v1har

This comment has been minimized.

Show comment Hide comment
@v1har

v1har Mar 15, 2017

Hey guys,

I just want to share my experience. If you can not use this code on your website, so the getJSON (submitting) is not working, try "https" instead of "http" in the form action! It helped me :)

I hope, it was a helpful information for you. ;)

v1har commented Mar 15, 2017

Hey guys,

I just want to share my experience. If you can not use this code on your website, so the getJSON (submitting) is not working, try "https" instead of "http" in the form action! It helped me :)

I hope, it was a helpful information for you. ;)

@mrmema

This comment has been minimized.

Show comment Hide comment
@mrmema

mrmema May 12, 2017

Hi,
need help pls, how to check if the email submitted is already on the campaign monitor list and get back a respond?
I am using the form to generate a coupon code ones the user provide the email BUT coupon must be generate ONLY if that email is unique on the campaign monitor list. Right now I am getting back all the time 200 even when the email is already on the list.
Thanks

mrmema commented May 12, 2017

Hi,
need help pls, how to check if the email submitted is already on the campaign monitor list and get back a respond?
I am using the form to generate a coupon code ones the user provide the email BUT coupon must be generate ONLY if that email is unique on the campaign monitor list. Right now I am getting back all the time 200 even when the email is already on the list.
Thanks

@vinayamk

This comment has been minimized.

Show comment Hide comment
@vinayamk

vinayamk May 24, 2017

Hi
Can any one please tel how to check email is already their in list , Currently form allows me to add same email id n number of times, it should say "Email is already exist use differnt one"

Thanks
Vinayak

Hi
Can any one please tel how to check email is already their in list , Currently form allows me to add same email id n number of times, it should say "Email is already exist use differnt one"

Thanks
Vinayak

@gentle-media

This comment has been minimized.

Show comment Hide comment
@gentle-media

gentle-media Jun 6, 2017

A lot of cries to add the response 'Email address already exist' to the 400 status. I also think this should be a default instead of resorting to the API for this.

gentle-media commented Jun 6, 2017

A lot of cries to add the response 'Email address already exist' to the 400 status. I also think this should be a default instead of resorting to the API for this.

@jnsprngs

This comment has been minimized.

Show comment Hide comment
@jnsprngs

jnsprngs Jun 16, 2017

Yo,

In case someone wanted a vanilla javascript example....

<form id="subForm" action="https://myaccount.createsend.com/t/d/s/mkriuy/" method="post">
	<label for="fieldEmail">Email</label><br />
	<input id="fieldEmail" name="cm-mkriuy-mkriuy" type="email" required />
	<button type="submit">Subscribe</button>
	<div id="messageDiv"></div>
</form>

var callbackFnName = function(res) {
	document.getElementById('messageDiv').innerHTML = res.Message;
	console.log(res);
}

var targetForm = document.getElementById('subForm');
targetForm.addEventListener('submit', function(e) {
	e.preventDefault();
	var emailField = document.getElementById('fieldEmail');
	var keyValues = [];
	keyValues.add = function(k,v) {
		this.push([encodeURIComponent(k),encodeURIComponent(v)].join('='));
		return this;
	};
	var query = function(arr) {
		return '?' + arr.join('&');
	};
	keyValues.add('callback', 'callbackFnName').add(emailField.name, emailField.value);
	var url = this.action + query(keyValues);
	var r = new XMLHttpRequest();
	r.open(this.method, url, true);
	r.onreadystatechange = function() {
		if(r.readyState === 4) {
			var res = document.createElement('script');
			res.type = 'text/javascript', res.async = 1, res.innerHTML = r.responseText;
			var s = document.getElementsByTagName('script')[0];
			s.parentNode.insertBefore(res,s);
		}
	}
	r.timeout = 3000;
	r.onerror = function() {console.log(this);}
	r.send();
}, false);

jnsprngs commented Jun 16, 2017

Yo,

In case someone wanted a vanilla javascript example....

<form id="subForm" action="https://myaccount.createsend.com/t/d/s/mkriuy/" method="post">
	<label for="fieldEmail">Email</label><br />
	<input id="fieldEmail" name="cm-mkriuy-mkriuy" type="email" required />
	<button type="submit">Subscribe</button>
	<div id="messageDiv"></div>
</form>

var callbackFnName = function(res) {
	document.getElementById('messageDiv').innerHTML = res.Message;
	console.log(res);
}

var targetForm = document.getElementById('subForm');
targetForm.addEventListener('submit', function(e) {
	e.preventDefault();
	var emailField = document.getElementById('fieldEmail');
	var keyValues = [];
	keyValues.add = function(k,v) {
		this.push([encodeURIComponent(k),encodeURIComponent(v)].join('='));
		return this;
	};
	var query = function(arr) {
		return '?' + arr.join('&');
	};
	keyValues.add('callback', 'callbackFnName').add(emailField.name, emailField.value);
	var url = this.action + query(keyValues);
	var r = new XMLHttpRequest();
	r.open(this.method, url, true);
	r.onreadystatechange = function() {
		if(r.readyState === 4) {
			var res = document.createElement('script');
			res.type = 'text/javascript', res.async = 1, res.innerHTML = r.responseText;
			var s = document.getElementsByTagName('script')[0];
			s.parentNode.insertBefore(res,s);
		}
	}
	r.timeout = 3000;
	r.onerror = function() {console.log(this);}
	r.send();
}, false);

@Factored-Dan

This comment has been minimized.

Show comment Hide comment
@Factored-Dan

Factored-Dan Aug 17, 2017

For anyone interested, you can't post data to the Campaign Monitor API using a custom sub domain with an SSL. For example, this would not work:
<form id="subForm" action="https://subdomain.domain.com/t/d/s/mkriuy/" method="post">
To make this work, use:
<form id="subForm" action="https://myaccount.createsend.com/t/d/s/mkriuy/" method="post">
Or this:
<form id="subForm" action="*.createsend.com/t/d/s/mkriuy/" method="post">
Hope this helps.

For anyone interested, you can't post data to the Campaign Monitor API using a custom sub domain with an SSL. For example, this would not work:
<form id="subForm" action="https://subdomain.domain.com/t/d/s/mkriuy/" method="post">
To make this work, use:
<form id="subForm" action="https://myaccount.createsend.com/t/d/s/mkriuy/" method="post">
Or this:
<form id="subForm" action="*.createsend.com/t/d/s/mkriuy/" method="post">
Hope this helps.

@ozywuli

This comment has been minimized.

Show comment Hide comment
@ozywuli

ozywuli Feb 16, 2018

Hey,

When I try to generate a sign up form, I get the following code:

<form id="subForm" class="js-cm-form" action="https://www.createsend.com/t/subscribeerror?description=" method="post" data-id="A61C50BEC994754B1D79C5819EC1255C90353F11B10B3CE4FF74762E36F3B9AADE7929ED766969AD206D8CAC4801738C7C14C8BE7D2BB89026D7629C3B405CC1">
    
    <p>
        <label for="fieldName">Name</label><br />
        <input id="fieldName" name="cm-name" type="text" />
    </p>
    <p>
        <label for="fieldEmail">Email</label><br />
        <input id="fieldEmail" class="js-cm-email-input" name="cm-ekuuhr-ekuuhr" type="email" required /> 
    </p>
    <p>
        <button class="js-cm-submit-button" type="submit">Subscribe</button> 
    </p>
</form>
    <script type="text/javascript" src="https://js.createsend1.com/javascript/copypastesubscribeformlogic.js"></script>

I removed the JS script from above and added the ajax code so now it looks like this

<form id="subForm" class="js-cm-form" action="https://www.createsend.com/t/subscribeerror?description=" method="post" data-id="A61C50BEC994754B1D79C5819EC1255C90353F11B10B3CE4FF74762E36F3B9AADE7929ED766969AD206D8CAC4801738C7C14C8BE7D2BB89026D7629C3B405CC1">
    
    <p>
        <label for="fieldName">Name</label><br />
        <input id="fieldName" name="cm-name" type="text" />
    </p>
    <p>
        <label for="fieldEmail">Email</label><br />
        <input id="fieldEmail" class="js-cm-email-input" name="cm-ekuuhr-ekuuhr" type="email" required /> 
    </p>
    <p>
        <button class="js-cm-submit-button" type="submit">Subscribe</button> 
    </p>
</form>

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script> 
<script>
    $(function () {
        $('#subForm').submit(function (e) {
            e.preventDefault();
            console.log(this.action + "?callback=?");
            $.getJSON(
            this.action + "?callback=?",
            $(this).serialize(),
            function (data) {
                console.log(data);
                if (data.Status === 400) {
                    alert("Error: " + data.Message);
                } else { // 200
                    alert("Success: " + data.Message);
                }
            });
        });
    });
</script>

But when I try to submit, I get the following error:

Refused to execute script from 'https://www.createsend.com/t/subscribeerror?description=?callback=jQuery16205281633389693063_1518739935858&cm-name=ozy&cm-ekuuhr-ekuuhr=ozy%40pxlagency.com&_=1518739942094' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled.

Next I tried changing the action value to a string that resembles the example:

<form action="http://pxlagency.createsend.com/t/r/s/ekuuhr/" method="post" id="subForm" data-id="A61C50BEC994754B1D79C5819EC1255C90353F11B10B3CE4FF74762E36F3B9AADE7929ED766969AD206D8CAC4801738C7C14C8BE7D2BB89026D7629C3B405CC1">
    <p>
        <label for="fieldName">Name</label><br />
        <input id="fieldName" name="cm-name" type="text" />
    </p>
    <p>
        <label for="fieldEmail">Email</label><br />
        <input id="fieldEmail" class="js-cm-email-input" name="cm-ekuuhr-ekuuhr" type="email" required /> 
    </p>
    <p>
        <button class="js-cm-submit-button" type="submit">Subscribe</button> 
    </p>
</form>

When I hit submit I get a success response. But when I check my subscriber list, I don't see the update.

Anybody have any clue what's going on?

Thanks

ozywuli commented Feb 16, 2018

Hey,

When I try to generate a sign up form, I get the following code:

<form id="subForm" class="js-cm-form" action="https://www.createsend.com/t/subscribeerror?description=" method="post" data-id="A61C50BEC994754B1D79C5819EC1255C90353F11B10B3CE4FF74762E36F3B9AADE7929ED766969AD206D8CAC4801738C7C14C8BE7D2BB89026D7629C3B405CC1">
    
    <p>
        <label for="fieldName">Name</label><br />
        <input id="fieldName" name="cm-name" type="text" />
    </p>
    <p>
        <label for="fieldEmail">Email</label><br />
        <input id="fieldEmail" class="js-cm-email-input" name="cm-ekuuhr-ekuuhr" type="email" required /> 
    </p>
    <p>
        <button class="js-cm-submit-button" type="submit">Subscribe</button> 
    </p>
</form>
    <script type="text/javascript" src="https://js.createsend1.com/javascript/copypastesubscribeformlogic.js"></script>

I removed the JS script from above and added the ajax code so now it looks like this

<form id="subForm" class="js-cm-form" action="https://www.createsend.com/t/subscribeerror?description=" method="post" data-id="A61C50BEC994754B1D79C5819EC1255C90353F11B10B3CE4FF74762E36F3B9AADE7929ED766969AD206D8CAC4801738C7C14C8BE7D2BB89026D7629C3B405CC1">
    
    <p>
        <label for="fieldName">Name</label><br />
        <input id="fieldName" name="cm-name" type="text" />
    </p>
    <p>
        <label for="fieldEmail">Email</label><br />
        <input id="fieldEmail" class="js-cm-email-input" name="cm-ekuuhr-ekuuhr" type="email" required /> 
    </p>
    <p>
        <button class="js-cm-submit-button" type="submit">Subscribe</button> 
    </p>
</form>

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script> 
<script>
    $(function () {
        $('#subForm').submit(function (e) {
            e.preventDefault();
            console.log(this.action + "?callback=?");
            $.getJSON(
            this.action + "?callback=?",
            $(this).serialize(),
            function (data) {
                console.log(data);
                if (data.Status === 400) {
                    alert("Error: " + data.Message);
                } else { // 200
                    alert("Success: " + data.Message);
                }
            });
        });
    });
</script>

But when I try to submit, I get the following error:

Refused to execute script from 'https://www.createsend.com/t/subscribeerror?description=?callback=jQuery16205281633389693063_1518739935858&cm-name=ozy&cm-ekuuhr-ekuuhr=ozy%40pxlagency.com&_=1518739942094' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled.

Next I tried changing the action value to a string that resembles the example:

<form action="http://pxlagency.createsend.com/t/r/s/ekuuhr/" method="post" id="subForm" data-id="A61C50BEC994754B1D79C5819EC1255C90353F11B10B3CE4FF74762E36F3B9AADE7929ED766969AD206D8CAC4801738C7C14C8BE7D2BB89026D7629C3B405CC1">
    <p>
        <label for="fieldName">Name</label><br />
        <input id="fieldName" name="cm-name" type="text" />
    </p>
    <p>
        <label for="fieldEmail">Email</label><br />
        <input id="fieldEmail" class="js-cm-email-input" name="cm-ekuuhr-ekuuhr" type="email" required /> 
    </p>
    <p>
        <button class="js-cm-submit-button" type="submit">Subscribe</button> 
    </p>
</form>

When I hit submit I get a success response. But when I check my subscriber list, I don't see the update.

Anybody have any clue what's going on?

Thanks

@brisa-pedronetto

This comment has been minimized.

Show comment Hide comment
@brisa-pedronetto

brisa-pedronetto Feb 19, 2018

I'm having the same issue as ozywuli, perhaps this code has to be updated to match the new "getsecuresubscribelink" step? Thank you!

I'm having the same issue as ozywuli, perhaps this code has to be updated to match the new "getsecuresubscribelink" step? Thank you!

@Snapto

This comment has been minimized.

Show comment Hide comment
@Snapto

Snapto Feb 28, 2018

I have just discovered this too. A bit desperate with Monday's go-live looming....

If anyone has any pointers, I'd really appreciate it.

Snapto commented Feb 28, 2018

I have just discovered this too. A bit desperate with Monday's go-live looming....

If anyone has any pointers, I'd really appreciate it.

@laurenhitchon

This comment has been minimized.

Show comment Hide comment
@laurenhitchon

laurenhitchon Mar 2, 2018

Please please, if anyone can help, I'd really appreciate it also!

Please please, if anyone can help, I'd really appreciate it also!

@dawidnawrot

This comment has been minimized.

Show comment Hide comment
@dawidnawrot

dawidnawrot Mar 19, 2018

@laurenhitchon @Snapto @brisa-pedronetto

New version of Campaign Monitor subscribe code works differently. As you can see code provides a js file (copypastesubscribeformlogic.js) which is responsible for sending data.

What has changed?
Previously it was just one static request to CM endpoint to subscribe a user and it was quite easy to make subscription requested by ajax. Now, it needs two separate requests to subscribe a user. First request is being done by ajax and is provided by CM (js file copypastesubscribeformlogic.js handles this request). This is the data that is being sent to CM:

URL: https://createsend.com//t/getsecuresubscribelink
Method: POST
Header: Content-type: application/x-www-form-urlencoded
Data: email=subscriber_email@example.com&data=data-id

subscriber_email@example.com is an e-mail provided in the form
data-id is an attribute taken from form tag provided by Campain Monitor code

In the response CM script gets a link with token. This is example of the link:

https://www.createsend.com/t/securedsubscribe?token=5A6DD7A94B9E0BCD68E622CFD904F4A09C640018E5595BCACC38D4308AA3F1A3564E98DFDA7CDBD5

When this link is returned (by ajax), form action attribute is being changed.
Initially form action tag is set to:
https://www.createsend.com/t/subscribeerror?description=

Right after the page has received a link with token form action attribute is changed to:
https://www.createsend.com/t/securedsubscribe?token=5A6DD7A94B9E0BCD68E622CFD904F4A09C640018E5595BCACC38D4308AA3F1A3564E98DFDA7CDBD5

At this moment form is being sent directly to CM and user is subscribed. So, this is how I ajaxyfied this new version of CM code (be aware this code needs jquery to work - maybe someone would like to make it in Vanilla JS):

var campaign = (function (c, d, $) {

  var body,
      form,
      form_id,
      config,
      successMessage;

  c.init = function () {

    body = $('body');
    form = body.find('#' + config.formSelector);
    form_id = form.attr('data-id');
    successMessage = $('#' + config.successSelector);
    successMessage.hide();

    // On form submit.
    form.submit(function (evt) {

      // Disable default form submit.
      evt.preventDefault();

      // Get e-mail value.
      email = $('input[type=email]', form).val();

      // Build request data for tokenRequest.
      request_data = "email=" + encodeURIComponent(email) + "&data=" + form_id;

      // Prepare tokenRequest.
      tokenRequest = new XMLHttpRequest();
      tokenRequest.open('POST', 'https://createsend.com//t/getsecuresubscribelink', true);
      tokenRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
      tokenRequest.send(request_data);

      // Ready state.
      tokenRequest.onreadystatechange = function() {
        if (this.readyState === 4) {
          if (this.status === 200) {
            // Having token and new submit url we can create new request to subscribe a user.
            subscribeRequest = new XMLHttpRequest();
            subscribeRequest.open('POST', this.responseText, true);
            subscribeRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            subscribeRequest.send(form.serialize());
            // On ready state call response function.
            subscribeRequest.onreadystatechange = function() {
              c.response(subscribeRequest);
            }
          } else {
            c.response(tokenRequest);
          }
        }
      }
    });
  };

  // Handle ajax response.
  c.response = function(request) {
    if (request.readyState === 4) {
      if (request.status === 200) {
        successMessage.show('slow');
      } else {
        form.prepend('<p class="error">' + config.errorMessage + '</p>');
      }
    }
  };

  // Private
  config = {
    formSelector: 'form',
    errorMessage: 'There was a problem submitting this form. Please try later.',
    successSelector: 'success',
  };

  return c;
  
}(campaign || {}, {}, jQuery));

(function () {
  campaign.init();
})(jQuery);

You can change your selector from form to anything that selects your form. For example: .container article form. You can also add an html element with success class and provide a info about successful submission, for example:

<div class="success">Your e-mail has been added to our list</div>

IMPORTANT:
Before you use this script get rid of original script provided by CM from emebed code.

dawidnawrot commented Mar 19, 2018

@laurenhitchon @Snapto @brisa-pedronetto

New version of Campaign Monitor subscribe code works differently. As you can see code provides a js file (copypastesubscribeformlogic.js) which is responsible for sending data.

What has changed?
Previously it was just one static request to CM endpoint to subscribe a user and it was quite easy to make subscription requested by ajax. Now, it needs two separate requests to subscribe a user. First request is being done by ajax and is provided by CM (js file copypastesubscribeformlogic.js handles this request). This is the data that is being sent to CM:

URL: https://createsend.com//t/getsecuresubscribelink
Method: POST
Header: Content-type: application/x-www-form-urlencoded
Data: email=subscriber_email@example.com&data=data-id

subscriber_email@example.com is an e-mail provided in the form
data-id is an attribute taken from form tag provided by Campain Monitor code

In the response CM script gets a link with token. This is example of the link:

https://www.createsend.com/t/securedsubscribe?token=5A6DD7A94B9E0BCD68E622CFD904F4A09C640018E5595BCACC38D4308AA3F1A3564E98DFDA7CDBD5

When this link is returned (by ajax), form action attribute is being changed.
Initially form action tag is set to:
https://www.createsend.com/t/subscribeerror?description=

Right after the page has received a link with token form action attribute is changed to:
https://www.createsend.com/t/securedsubscribe?token=5A6DD7A94B9E0BCD68E622CFD904F4A09C640018E5595BCACC38D4308AA3F1A3564E98DFDA7CDBD5

At this moment form is being sent directly to CM and user is subscribed. So, this is how I ajaxyfied this new version of CM code (be aware this code needs jquery to work - maybe someone would like to make it in Vanilla JS):

var campaign = (function (c, d, $) {

  var body,
      form,
      form_id,
      config,
      successMessage;

  c.init = function () {

    body = $('body');
    form = body.find('#' + config.formSelector);
    form_id = form.attr('data-id');
    successMessage = $('#' + config.successSelector);
    successMessage.hide();

    // On form submit.
    form.submit(function (evt) {

      // Disable default form submit.
      evt.preventDefault();

      // Get e-mail value.
      email = $('input[type=email]', form).val();

      // Build request data for tokenRequest.
      request_data = "email=" + encodeURIComponent(email) + "&data=" + form_id;

      // Prepare tokenRequest.
      tokenRequest = new XMLHttpRequest();
      tokenRequest.open('POST', 'https://createsend.com//t/getsecuresubscribelink', true);
      tokenRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
      tokenRequest.send(request_data);

      // Ready state.
      tokenRequest.onreadystatechange = function() {
        if (this.readyState === 4) {
          if (this.status === 200) {
            // Having token and new submit url we can create new request to subscribe a user.
            subscribeRequest = new XMLHttpRequest();
            subscribeRequest.open('POST', this.responseText, true);
            subscribeRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            subscribeRequest.send(form.serialize());
            // On ready state call response function.
            subscribeRequest.onreadystatechange = function() {
              c.response(subscribeRequest);
            }
          } else {
            c.response(tokenRequest);
          }
        }
      }
    });
  };

  // Handle ajax response.
  c.response = function(request) {
    if (request.readyState === 4) {
      if (request.status === 200) {
        successMessage.show('slow');
      } else {
        form.prepend('<p class="error">' + config.errorMessage + '</p>');
      }
    }
  };

  // Private
  config = {
    formSelector: 'form',
    errorMessage: 'There was a problem submitting this form. Please try later.',
    successSelector: 'success',
  };

  return c;
  
}(campaign || {}, {}, jQuery));

(function () {
  campaign.init();
})(jQuery);

You can change your selector from form to anything that selects your form. For example: .container article form. You can also add an html element with success class and provide a info about successful submission, for example:

<div class="success">Your e-mail has been added to our list</div>

IMPORTANT:
Before you use this script get rid of original script provided by CM from emebed code.

@macaroons

This comment has been minimized.

Show comment Hide comment
@macaroons

macaroons Mar 21, 2018

Came searching for a way to ajaxify the new CM form and @dawidnawrot has truly saved the day. Thanks! The above code definitely works for the new forms.

macaroons commented Mar 21, 2018

Came searching for a way to ajaxify the new CM form and @dawidnawrot has truly saved the day. Thanks! The above code definitely works for the new forms.

@dawidnawrot

This comment has been minimized.

Show comment Hide comment
@dawidnawrot

dawidnawrot Mar 28, 2018

@macaroons glad to help :)

@macaroons glad to help :)

@coneilltmx

This comment has been minimized.

Show comment Hide comment
@coneilltmx

coneilltmx Apr 11, 2018

Followed all your instructions but cant seem to get my code to work. Any ideas? The code is as follows

Form:

<form id="Subform" class="js-cm-form" action="https://www.createsend.com/t/subscribeerror?description=" method="post" data-id="XXXXXXXXXXXXXXXXXXXXXX">
<label for="fieldEmail">Email</label><br />
<input id="fieldEmail" class="" name="cm-zjikdu-zjikdu" type="email" required /> 
<button class="btn btn-primary btn-block" type="submit">Subscribe</button> 
</form>

Javascript:

         <script type="text/javascript" src="js/jquery.min.js"></script> 
              <script type="text/javascript">
              var campaign = (function (c, d, $) {

               var body,
                   form,
                   form_id,
                   config,
                   successMessage;

               c.init = function () {

                   body = $('body');
                   form = body.find('#' + config.formSelector);
                   form_id = form.attr('data-id');
                   successMessage = $('#' + config.successSelector);
                   successMessage.hide();

                   // On form submit.
                   form.submit(function (evt) {

                       // Disable default form submit.
                       evt.preventDefault();

                       // Get e-mail value.
                       email = $('input[type=email]', form).val();

                       // Build request data for tokenRequest.
                       request_data = "email=" + encodeURIComponent(email) + "&data=" + form_id;

                       // Prepare tokenRequest.
                       tokenRequest = new XMLHttpRequest();
                       tokenRequest.open('POST', 'https://createsend.com//t/getsecuresubscribelink', true);
                       tokenRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                       tokenRequest.send(request_data);

                       // Ready state.
                       tokenRequest.onreadystatechange = function () {
                           if (this.readyState === 4) {
                               if (this.status === 200) {
                                   // Having token and new submit url we can create new request to subscribe a user.
                                   subscribeRequest = new XMLHttpRequest();
                                   subscribeRequest.open('POST', this.responseText, true);
                                   subscribeRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                                   subscribeRequest.send(form.serialize());
                                   // On ready state call response function.
                                   subscribeRequest.onreadystatechange = function () {
                                       c.response(subscribeRequest);
                                   }
                               } else {
                                   c.response(tokenRequest);
                               }
                           }
                       }
                   });
               };

               // Handle ajax response.
               c.response = function (request) {
                   if (request.readyState === 4) {
                       if (request.status === 200) {
                           successMessage.show('slow');
                       } else {
                           form.prepend('<p class="error">' + config.errorMessage + '</p>');
                       }
                   }
               };

               // Private
               config = {
                   formSelector: 'Subform',
                   errorMessage: 'There was a problem submitting this form. Please try later.',
                   successSelector: 'success',
               };

               return c;

           }(campaign || {}, {}, jQuery));

           (function () {
               campaign.init();
           })(jQuery);

       </script>

Upon clicking the forms submit button it doesn't go anywhere. With the CM included javascript it jumps to a CM confirmation page.

coneilltmx commented Apr 11, 2018

Followed all your instructions but cant seem to get my code to work. Any ideas? The code is as follows

Form:

<form id="Subform" class="js-cm-form" action="https://www.createsend.com/t/subscribeerror?description=" method="post" data-id="XXXXXXXXXXXXXXXXXXXXXX">
<label for="fieldEmail">Email</label><br />
<input id="fieldEmail" class="" name="cm-zjikdu-zjikdu" type="email" required /> 
<button class="btn btn-primary btn-block" type="submit">Subscribe</button> 
</form>

Javascript:

         <script type="text/javascript" src="js/jquery.min.js"></script> 
              <script type="text/javascript">
              var campaign = (function (c, d, $) {

               var body,
                   form,
                   form_id,
                   config,
                   successMessage;

               c.init = function () {

                   body = $('body');
                   form = body.find('#' + config.formSelector);
                   form_id = form.attr('data-id');
                   successMessage = $('#' + config.successSelector);
                   successMessage.hide();

                   // On form submit.
                   form.submit(function (evt) {

                       // Disable default form submit.
                       evt.preventDefault();

                       // Get e-mail value.
                       email = $('input[type=email]', form).val();

                       // Build request data for tokenRequest.
                       request_data = "email=" + encodeURIComponent(email) + "&data=" + form_id;

                       // Prepare tokenRequest.
                       tokenRequest = new XMLHttpRequest();
                       tokenRequest.open('POST', 'https://createsend.com//t/getsecuresubscribelink', true);
                       tokenRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                       tokenRequest.send(request_data);

                       // Ready state.
                       tokenRequest.onreadystatechange = function () {
                           if (this.readyState === 4) {
                               if (this.status === 200) {
                                   // Having token and new submit url we can create new request to subscribe a user.
                                   subscribeRequest = new XMLHttpRequest();
                                   subscribeRequest.open('POST', this.responseText, true);
                                   subscribeRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                                   subscribeRequest.send(form.serialize());
                                   // On ready state call response function.
                                   subscribeRequest.onreadystatechange = function () {
                                       c.response(subscribeRequest);
                                   }
                               } else {
                                   c.response(tokenRequest);
                               }
                           }
                       }
                   });
               };

               // Handle ajax response.
               c.response = function (request) {
                   if (request.readyState === 4) {
                       if (request.status === 200) {
                           successMessage.show('slow');
                       } else {
                           form.prepend('<p class="error">' + config.errorMessage + '</p>');
                       }
                   }
               };

               // Private
               config = {
                   formSelector: 'Subform',
                   errorMessage: 'There was a problem submitting this form. Please try later.',
                   successSelector: 'success',
               };

               return c;

           }(campaign || {}, {}, jQuery));

           (function () {
               campaign.init();
           })(jQuery);

       </script>

Upon clicking the forms submit button it doesn't go anywhere. With the CM included javascript it jumps to a CM confirmation page.

@blackbird74

This comment has been minimized.

Show comment Hide comment
@blackbird74

blackbird74 Apr 20, 2018

For some reason the form was still being submitted the 'default' way and after subscribing I was taken to the campaign monitor confirmation page, instead of just staying on the page with the form.

Changing the following line:

form.submit(function (evt) {

to

$(document).on('click', '.js-cm-submit-button', function(evt){

worked for me (.js-cm-submit-button is the class of the submit button in the form).

Probably a better way to do this but I'm pressed for time :)

For some reason the form was still being submitted the 'default' way and after subscribing I was taken to the campaign monitor confirmation page, instead of just staying on the page with the form.

Changing the following line:

form.submit(function (evt) {

to

$(document).on('click', '.js-cm-submit-button', function(evt){

worked for me (.js-cm-submit-button is the class of the submit button in the form).

Probably a better way to do this but I'm pressed for time :)

@asgharabbas

This comment has been minimized.

Show comment Hide comment
@asgharabbas

asgharabbas Apr 20, 2018

@dawidnawrot how we call this javascript function on form submit ajax...
var campaign = (function (c, d, $) {

           var body,
               form,
               form_id,
               config,
               successMessage;

           c.init = function () {

               body = $('body');
               form = body.find('#' + config.formSelector);
               form_id = form.attr('data-id');
               successMessage = $('#' + config.successSelector);
               successMessage.hide();

               // On form submit.
               form.submit(function (evt) {

                   // Disable default form submit.
                   evt.preventDefault();

                   // Get e-mail value.
                   email = $('input[type=email]', form).val();

                   // Build request data for tokenRequest.
                   request_data = "email=" + encodeURIComponent(email) + "&data=" + form_id;

                   // Prepare tokenRequest.
                   tokenRequest = new XMLHttpRequest();
                   tokenRequest.open('POST', 'https://createsend.com//t/getsecuresubscribelink', true);
                   tokenRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                   tokenRequest.send(request_data);

                   // Ready state.
                   tokenRequest.onreadystatechange = function () {
                       if (this.readyState === 4) {
                           if (this.status === 200) {
                               // Having token and new submit url we can create new request to subscribe a user.
                               subscribeRequest = new XMLHttpRequest();
                               subscribeRequest.open('POST', this.responseText, true);
                               subscribeRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                               subscribeRequest.send(form.serialize());
                               // On ready state call response function.
                               subscribeRequest.onreadystatechange = function () {
                                   c.response(subscribeRequest);
                               }
                           } else {
                               c.response(tokenRequest);
                           }
                       }
                   }
               });
           };

           // Handle ajax response.
           c.response = function (request) {
               if (request.readyState === 4) {
                   if (request.status === 200) {
                       successMessage.show('slow');
                   } else {
                       form.prepend('<p class="error">' + config.errorMessage + '</p>');
                   }
               }
           };

           // Private
           config = {
               formSelector: 'Subform',
               errorMessage: 'There was a problem submitting this form. Please try later.',
               successSelector: 'success',
           };

           return c;

       }(campaign || {}, {}, jQuery));

       (function () {
           campaign.init();
       })(jQuery);

asgharabbas commented Apr 20, 2018

@dawidnawrot how we call this javascript function on form submit ajax...
var campaign = (function (c, d, $) {

           var body,
               form,
               form_id,
               config,
               successMessage;

           c.init = function () {

               body = $('body');
               form = body.find('#' + config.formSelector);
               form_id = form.attr('data-id');
               successMessage = $('#' + config.successSelector);
               successMessage.hide();

               // On form submit.
               form.submit(function (evt) {

                   // Disable default form submit.
                   evt.preventDefault();

                   // Get e-mail value.
                   email = $('input[type=email]', form).val();

                   // Build request data for tokenRequest.
                   request_data = "email=" + encodeURIComponent(email) + "&data=" + form_id;

                   // Prepare tokenRequest.
                   tokenRequest = new XMLHttpRequest();
                   tokenRequest.open('POST', 'https://createsend.com//t/getsecuresubscribelink', true);
                   tokenRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                   tokenRequest.send(request_data);

                   // Ready state.
                   tokenRequest.onreadystatechange = function () {
                       if (this.readyState === 4) {
                           if (this.status === 200) {
                               // Having token and new submit url we can create new request to subscribe a user.
                               subscribeRequest = new XMLHttpRequest();
                               subscribeRequest.open('POST', this.responseText, true);
                               subscribeRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                               subscribeRequest.send(form.serialize());
                               // On ready state call response function.
                               subscribeRequest.onreadystatechange = function () {
                                   c.response(subscribeRequest);
                               }
                           } else {
                               c.response(tokenRequest);
                           }
                       }
                   }
               });
           };

           // Handle ajax response.
           c.response = function (request) {
               if (request.readyState === 4) {
                   if (request.status === 200) {
                       successMessage.show('slow');
                   } else {
                       form.prepend('<p class="error">' + config.errorMessage + '</p>');
                   }
               }
           };

           // Private
           config = {
               formSelector: 'Subform',
               errorMessage: 'There was a problem submitting this form. Please try later.',
               successSelector: 'success',
           };

           return c;

       }(campaign || {}, {}, jQuery));

       (function () {
           campaign.init();
       })(jQuery);
@asgharabbas

This comment has been minimized.

Show comment Hide comment
@asgharabbas

asgharabbas Apr 21, 2018

<script type="text/javascript" src="https://js.createsend1.com/javascript/copypastesubscribeformlogic.js"></script>

download the code from this url "https://js.createsend1.com/javascript/copypastesubscribeformlogic.js" and create your own js file and paste it.
Then, do these changes in the c.onreadystatechange then it will works like a charm.....
c.onreadystatechange=function(){
if (this.readyState === 4) {
if (this.status === 200) {
// Having token and new submit url we can create new request to subscribe a user.
subscribeRequest = new XMLHttpRequest();
subscribeRequest.open('POST', this.responseText, true);
subscribeRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
subscribeRequest.send($("#subForm").serialize());
// On ready state call response function.
subscribeRequest.onreadystatechange = function() {
alert("success");
}
} else {
alert("error");
}
}
}

<script type="text/javascript" src="https://js.createsend1.com/javascript/copypastesubscribeformlogic.js"></script>

download the code from this url "https://js.createsend1.com/javascript/copypastesubscribeformlogic.js" and create your own js file and paste it.
Then, do these changes in the c.onreadystatechange then it will works like a charm.....
c.onreadystatechange=function(){
if (this.readyState === 4) {
if (this.status === 200) {
// Having token and new submit url we can create new request to subscribe a user.
subscribeRequest = new XMLHttpRequest();
subscribeRequest.open('POST', this.responseText, true);
subscribeRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
subscribeRequest.send($("#subForm").serialize());
// On ready state call response function.
subscribeRequest.onreadystatechange = function() {
alert("success");
}
} else {
alert("error");
}
}
}

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