Skip to content

Instantly share code, notes, and snippets.

@callaginn
Last active December 4, 2020 17:08
Show Gist options
  • Save callaginn/ed2276813cad1640e70d67bd067f5966 to your computer and use it in GitHub Desktop.
Save callaginn/ed2276813cad1640e70d67bd067f5966 to your computer and use it in GitHub Desktop.
FormCarry Fetch Submission with Custom Response
// jshint strict:false, undef:false, unused:false
/*/
FormCarry Ajax Functions
Last Updated 2020-12-04
// How to Initialize
ajaxFormInit().then(json => {
console.log(json.form);
console.log(json.response);
json.alert.innerHTML = json.msg;
json.alert.className = "alert alert-success";
}).catch(error => {
console.log(error.form);
console.error(error.response);
error.alert.innerHTML = error.msg;
error.alert.className = "alert alert-danger";
});
/*/
var getUrlString = data => Object.entries(data).map(e => e.join('=')).join('&');
function translate(key, lang) {
lang = lang || document.documentElement.getAttribute("lang");
var translations = {
en: {
success: "Thank you for contacting us. We will be in touch.",
error: "We experienced an error processing your form. Please make sure ALL required fields are complete and try again."
},
es: {
success: "Gracias por contactarnos. En breve nos comunicaremos con usted.",
error: "Estamos presentando dificultades para procesar su mensaje. Por favor complete todas las areas de información requeridas e intentelo nuevamente."
}
}
return translations[lang][key];
}
function ajaxFormInit(selector, debug) {
selector = selector || '[data-processor=formcarry]';
debug = debug || getUrlParameter('debug');
return new Promise((resolve, reject) => {
document.querySelectorAll(selector).forEach(form => {
var el = {
"form": form,
"alert": form.querySelector('[data-alert="status"]'),
"inputs": form.querySelectorAll("[name]"),
"btn": form.querySelector(".btn-submit")
}
var btn = el.btn,
action = form.getAttribute("data-post"),
recipient = form.querySelector('[name=recipient]');
// Set default values
form.setAttribute("method", "POST");
form.setAttribute("accept-charset", "UTF-8");
if (recipient) {
if (debug) {
console.log("Has Recipient!");
}
// Optional: Switch FormCarry action with dropdown
recipient.addEventListener("change", el => {
action = el.target.options[el.target.selectedIndex].getAttribute("data-action");
if (action) {
btn.removeAttribute("disabled");
form.setAttribute("data-post", action);
} else {
btn.setAttribute("disabled", true);
form.removeAttribute("data-post");
}
if (debug) {
console.log(action);
}
});
}
// Submit data via Fetch
form.addEventListener('submit', e => {
e.preventDefault();
var data = getValues(form);
fetch(action, {
method: 'POST',
headers: {'Content-Type': 'application/json', 'Accept': 'application/json'},
body: JSON.stringify(data)
}).then(response => {
// Return response promise to next .then statement
return response.json();
}).then(json => {
el.response = json;
el.msg = translate("success");
// Resolve final values
resolve(el);
}).catch(error => {
el.response = error;
el.msg = translate("error");
reject(el);
});
});
});
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment