Created
July 13, 2019 01:20
-
-
Save verticalgrain/078b22c5493724ad8f3f1d649ef38287 to your computer and use it in GitHub Desktop.
Mailchimp Asynchronous Submit
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Submit mailchimp form asynchronously | |
* Modify mailchimp form action URL - replace subscribe/post? with subscribe/post-json? | |
* Example: Replace https://bevcanna.us7.list-manage.com/subscribe/post? with https://bevcanna.us7.list-manage.com/subscribe/post-json? | |
*/ | |
function validateEmail(Email) { | |
var pattern = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/; | |
return $.trim(Email).match(pattern) ? true : false; | |
} | |
function formHandler(){ | |
var $form = $('form.mailchimp-ajax-submit'), | |
$emailField = $('form.mailchimp-ajax-submit #mce-EMAIL'), | |
$notificationArea = $('.js-notification'), | |
$submitButton = $('form.mailchimp-ajax-submit #mc-embedded-subscribe'); | |
$submitButton.click(function(e) { | |
e.preventDefault(); | |
var emailValue = $emailField.val(); | |
if ((emailValue == '')) { | |
$notificationArea.empty(); | |
$notificationArea.append('Please fill in your email address'); | |
} else if ( validateEmail(emailValue) === false ) { | |
$notificationArea.empty(); | |
$notificationArea.append('Please enter a valid email address'); | |
} else { | |
subscribe_mailchimp($form); | |
} | |
}); | |
} | |
function subscribe_mailchimp($form) { | |
var $notificationArea = $('.js-notification'); | |
$.ajax({ | |
type: $form.attr('method'), | |
url: $form.attr('action'), | |
data: $form.serialize(), | |
cache : false, | |
dataType : 'json', | |
contentType: "application/json; charset=utf-8", | |
error : function(err) { | |
$notificationArea.html('Could not connect to the Mailchimp server. Please try again later.') | |
}, | |
success : function(data) { | |
if (data.result != "success") { | |
$notificationArea.html(data.msg) | |
} else { | |
$notificationArea.html('Thanks for signing up. Please check your inbox.') | |
} | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment