Skip to content

Instantly share code, notes, and snippets.

@panphora
Last active May 6, 2022 19:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save panphora/8fcbae7b753eb8131f4b946581bf6f6e to your computer and use it in GitHub Desktop.
Save panphora/8fcbae7b753eb8131f4b946581bf6f6e to your computer and use it in GitHub Desktop.
function addSubscriberToMailChimp ({email, firstName, formAction, onSuccess, onError}) {
// Get url for mailchimp
let url = (formAction || "").replace('/post?', '/post-json?');
// add email and first name
url += `&EMAIL=${encodeURIComponent(email)}&FNAME=${encodeURIComponent(firstName)}`;
// Create & add post script to the DOM
let script = document.createElement('script');
script.src = url + "&c=mailchimpCallback";
document.body.appendChild(script);
// Callback function
let callback = 'mailchimpCallback';
window[callback] = function(res) {
// Remove script from the DOM after it's called
delete window[callback];
document.body.removeChild(script);
// Display notices
if (res.result === "success") {
onSuccess(res);
} else {
onError(res);
}
};
}
addSubscriberToMailChimp({
firstName: "xxxxxxx",
email: "xxxxxx@example.com",
// create an "embedded form" in mailchimp, then paste the form's action here
formAction: "https://xxxxxxxx.us8.list-manage.com/subscribe/post?u=xxxxxxxxxxx&id=xxxxxxxxxx",
onSuccess: (res) => console.log("success", res),
onError: (res) => console.log("error", res)
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment