Skip to content

Instantly share code, notes, and snippets.

@jackmcpickle
Forked from jdennes/LICENSE
Last active November 26, 2015 04:27
Show Gist options
  • Save jackmcpickle/cdb5ea177966f927dcb1 to your computer and use it in GitHub Desktop.
Save jackmcpickle/cdb5ea177966f927dcb1 to your computer and use it in GitHub Desktop.
Subscribing to a Campaign Monitor list using AJAX
<!-- 1. Take your Campaign Monitor subscribe form as generated from within your account: -->
<form action="http://myaccount.createsend.com/t/r/s/aljhk/" method="post" id="cm_form">
<div>
<label for="name">Name:</label><br /><input type="text" name="cm-name" id="name" required /><br />
<label for="aljhk-aljhk">Email:</label><br /><input type="email" name="cm-aljhk-aljhk" id="aljhk-aljhk" required /><br />
<button type="submit" class="button" id="submit_form" disabled>Subscribe</button>
<p id="message"></p>
</div>
</form>
<!-- 2. Add some JavaScript -->
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.14.0/jquery.validate.min.js"></script>
<script type="text/javascript">
$(function () {
var $submitButton = $('#submit_form'),
$form = $('#cm_form'),
$message = $('#message');
var checkIfFormValid = function() {
if ($form.valid()) {
$submitButton.prop('disabled', false);
} else {
$submitButton.prop('disabled', true);
}
};
$form.validate();
$form.on('change', checkIfFormValid);
$form.on('submit', function (e) {
e.preventDefault();
$submitButton.text('Sending').prop('disabled', true);
if ($form.valid()) {
$.ajax({
url: this.action,
method: this.method,
dataType: "jsonp",
data: $(this).serialize(),
success: function(data) {
$submitButton.text('Done');
$message.text("Success:" + data.Message);
},
error: function(jqXHR, textStatus, errorThrown) {
$message.text("Error: " + textStatus);
}
});
}
});
});
</script>
<!-- 3. You have an AJAX subscribe form! -->
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment