Skip to content

Instantly share code, notes, and snippets.

@atav32
Created August 29, 2018 22:27
Show Gist options
  • Save atav32/4a38972793bdbca92e54e8902a6def28 to your computer and use it in GitHub Desktop.
Save atav32/4a38972793bdbca92e54e8902a6def28 to your computer and use it in GitHub Desktop.
POST form data to HubSpot API
// API documentation, https://developers.hubspot.com/docs/methods/forms/submit_form
const convertToFormData = (data) => Object.entries(data).reduce((formData, entry) => {
const [key, value] = entry;
if (value !== null && typeof value === 'object') {
formData.append(key, JSON.stringify(value));
} else {
formData.append(key, value);
}
return formData;
}, new FormData());
// extracts the tracking cookie placed by the HubSpot tracking library
const extractHubspotCookie = () => (
document.cookie.split(';').filter((item) => item.includes('hubspotutk='))[0].split('=')[1]
);
// form submit handler
submitToHubspot = (data) => {
const formData = {
...data,
hs_context: {
hutk: extractHubspotCookie(),
pageUrl: window.location.href,
}
};
const formDataUrlParams = new URLSearchParams(convertToFormData(formData));
fetch('https://forms.hubspot.com/uploads/form/v2/:portal_id/:form_guid', {
method: 'POST',
mode: 'no-cors',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: formDataUrlParams
}).then(response => {
// Thank the user for submitting the form
// HubSpot API only ever returns a 204, no 200 and no error codes
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment