Created
April 7, 2023 18:17
-
-
Save panphora/035967a28cddf07ae46ac4c3a51eab04 to your computer and use it in GitHub Desktop.
How to use AJAX POST or JSONP to send subscribers to ConvertKit, Mailchimp, Mailerlite, SendFox, and EmailOctopus on the front-end
This file contains hidden or 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
import toastNotification from "./toast-notification"; | |
import {callEventCallbacks} from "./event-callbacks"; | |
let emailPlatforms = [ | |
{ | |
urlIncludes: ".convertkit.com/forms", | |
subscribeFunction: addSubscriberToConvertKit | |
}, | |
{ | |
urlIncludes: ".list-manage.com/subscribe", | |
subscribeFunction: addSubscriberToMailChimp | |
}, | |
{ | |
urlIncludes: ".mailerlite.com/webforms", | |
subscribeFunction: addSubscriberToMailerLite | |
}, | |
{ | |
urlIncludes: "sendfox.com/form", | |
subscribeFunction: addSubscriberToSendFox | |
}, | |
{ | |
urlIncludes: "eocampaign1.com/form", | |
subscribeFunction: addSubscriberToEmailOctopus | |
} | |
]; | |
export default function sendToEmailPlatform ({ | |
signupFormAction, | |
newEmailSignupSuccessMessage, | |
newEmailSignupErrorMessage, | |
firstName, | |
}) { | |
let subscribeFunction = getSubscribeFunction(signupFormAction); | |
if (subscribeFunction) { | |
subscribeFunction({ | |
firstName, | |
email, | |
signupFormAction, | |
onSuccess: () => { | |
toastNotification(newEmailSignupSuccessMessage); | |
callEventCallbacks("onNewEmailSignup", { | |
firstName, | |
email, | |
wasSuccessful: true | |
}); | |
}, | |
onError: () => { | |
toastNotification(newEmailSignupErrorMessage, {backgroundColor: "#c41f33"}); | |
callEventCallbacks("onNewEmailSignup", { | |
firstName, | |
email, | |
wasSuccessful: false | |
}); | |
} | |
}); | |
} | |
} | |
function getSubscribeFunction (signupFormAction) { | |
for (let i = 0; i < emailPlatforms.length; i++) { | |
let emailPlatform = emailPlatforms[i]; | |
if (signupFormAction.includes(emailPlatform.urlIncludes)) { | |
return emailPlatform.subscribeFunction; | |
} | |
} | |
} | |
function addSubscriberToConvertKit ({firstName, email, signupFormAction, onSuccess, onError}) { | |
let subscriberData = {}; | |
if (firstName) { | |
subscriberData["first_name"] = firstName; | |
} | |
if (email) { | |
subscriberData["email_address"] = email; | |
} else { | |
onError({error: "No email"}); | |
return; | |
} | |
fetch(signupFormAction, { | |
method: "POST", | |
body: JSON.stringify(subscriberData), | |
headers: { | |
"Accept": "application/json", | |
"Content-Type": "application/json" | |
} | |
}) | |
.then(res => res.json()) | |
.then(res => { | |
if (res.status === "success") { | |
onSuccess(res); | |
} else if (res.status === "quarantined") { | |
window.open(res.url, '_blank'); | |
} else { | |
// TIP for ConvertKit: | |
// trigger an "invalid email" error if res.errors.fields.includes("email_address") | |
onError(res); | |
} | |
}) | |
.catch(err => { | |
onError(err); | |
}); | |
} | |
function addSubscriberToSendFox ({firstName, email, signupFormAction, onSuccess, onError}) { | |
var formData = new FormData(); | |
if (firstName) { | |
formData.append("first_name", firstName); | |
} | |
if (email) { | |
formData.append("email", email); | |
} else { | |
onError({error: "No email"}); | |
return; | |
} | |
formData.append("a_password", ""); | |
fetch(signupFormAction, { | |
method: "POST", | |
body: formData, | |
headers: { | |
"X-Requested-With": "XMLHttpRequest" | |
} | |
}) | |
.then(res => res.json()) | |
.then(res => { | |
if (!res.errors) { | |
if (res.redirect_url) { | |
window.location.href = res.redirect_url; | |
} else { | |
onSuccess(res); | |
} | |
} else { | |
onError(res); | |
} | |
}) | |
.catch(err => { | |
onError(err); | |
}); | |
} | |
function addSubscriberToEmailOctopus ({firstName, email, signupFormAction, onSuccess, onError}) { | |
signupFormAction = (signupFormAction || "").replace(/\.js$/, ""); | |
let data = ""; | |
if (email) { | |
data += `field_0=${encodeURIComponent(email)}`; | |
} else { | |
onError({error: "No email"}); | |
return; | |
} | |
if (firstName) { | |
data += `&field_1=${encodeURIComponent(firstName)}`; | |
} | |
fetch(signupFormAction, { | |
method: "POST", | |
body: data, | |
headers: { | |
"content-type": "application/x-www-form-urlencoded" | |
} | |
}) | |
.then(res => res.json()) | |
.then(res => { | |
if (res.success) { | |
onSuccess(res); | |
} else { | |
onError(res); | |
} | |
}) | |
.catch(err => { | |
onError(err); | |
}); | |
} | |
function addSubscriberToMailChimp ({firstName, email, signupFormAction, onSuccess, onError}) { | |
// Get url for mailchimp | |
let url = (signupFormAction || "").replace('/post?', '/post-json?'); | |
// add first name | |
if (firstName) { | |
url += `&FNAME=${encodeURIComponent(firstName)}`; | |
} | |
// add email | |
if (email) { | |
url += `&EMAIL=${encodeURIComponent(email)}`; | |
} else { | |
onError({error: "No email"}); | |
return; | |
} | |
jsonp(url, "c", res => { | |
if (res.result === "success") { | |
onSuccess(res); | |
} else { | |
onError(res); | |
} | |
}); | |
} | |
function addSubscriberToMailerLite ({firstName, email, signupFormAction, onSuccess, onError}) { | |
let url = "https://static.mailerlite.com/webforms/submit/a1p0p0?&fields%5Bemail%5D=sammy%40storylog.com&fields%5Bname%5D=sammy&ml-submit=1&anticsrf=true&ajax=1&guid=a6da0574-d30a-c521-74a3-40c611af0853"; | |
// add first name | |
if (firstName) { | |
url += `&fields%5Bname%5D=${encodeURIComponent(firstName)}`; | |
} | |
// add email | |
if (email) { | |
url += `&fields%5Bemail%5D=${encodeURIComponent(email)}`; | |
} else { | |
onError({error: "No email"}); | |
return; | |
} | |
url += `&ml-submit=1&anticsrf=true&ajax=1&guid=${guid()}`; | |
jsonp(url, "callback", res => { | |
if (res.success === true) { | |
onSuccess(res); | |
} else { | |
onError(res); | |
} | |
}); | |
} | |
function jsonp (url, callbackName = "callback", callback) { | |
// Create & add post script to the DOM | |
let emailSubscriberScript = document.createElement('script'); | |
emailSubscriberScript.src = url + `&${callbackName}=politePopEmailSubscriberCallback`; | |
document.body.appendChild(emailSubscriberScript); | |
// Callback function | |
let emailSubscriberCallback = 'politePopEmailSubscriberCallback'; | |
window[emailSubscriberCallback] = function(res) { | |
// Remove script from the DOM after it's called | |
delete window[emailSubscriberCallback]; | |
document.body.removeChild(emailSubscriberScript); | |
callback(res); | |
}; | |
} | |
function guid () { | |
function a() { | |
return Math.floor(65536 * (1 + Math.random())).toString(16).substring(1); | |
} | |
return a() + a() + "-" + a() + "-" + a() + "-" + a() + "-" + a() + a() + a(); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment