Skip to content

Instantly share code, notes, and snippets.

@robertainslie
robertainslie / submit-to-hubspot-forms-api-with-javascript.md
Last active April 9, 2024 02:02
Submitting to the HubSpot Forms API with JavaScript

Overview

This tutorial will walk you through how to submit to the HubSpot Forms API using Javascript. Check out the documentation for submitting to the Forms API.

  • It will use vanilla JS (i.e. no libraries or frameworks) and will provide example code.
  • It will assume that you are familiar with HubSpot, HubSpot Forms, and that the HubSpot Tracking Code is on the page.

A note on the HubSpot cookie: hubspotutk

The HubSpot tracking code is a javascript snippet that is placed on websites. It anonymously collects website visit data, similar to Google Analytics. This anonymous visit data can be associated to HubSpot Contact record through a few means, including sending a usertoken value when submitting data to the Forms API. The tracking code generates a cookie containing a unique usertoken called hubspotutk. The value of hubspotutk will be submitted in our form submission as hutk. HubSpot uses this cookie value to connect visito

Sometimes, a customer might have data being loaded programmatically into a page and want that data to write to form fields. Because HubSpot Forms are generated programmatically with React, there need to be two considerations in your code that make setting fields programmatically more difficult:

  1. The data must be inserted after the form has finished loading
  2. Data that is inserted programmatically must have a js "change" event fired on the field in order to propagate the change into the React data layer

These two considerations are handled separately.

Inserting form data after form load

There are two methods to handle this - one including jQuery and one using vanilla javascript

{% set example_contact = 801 %}
{% set example_industry = "Hospitality" %}
{% set example_fee_range = "$100,000-$250,000" %}
<!-- contact.franchise_budget contact.industry-->
{% set associated_recommended_franchises = crm_associations(contact.hs_object_id,'USER_DEFINED','36','','franchise_name,industry,initiation_fee',true) %}
{% for franchise in associated_recommended_franchises.results %}
<p style="background-color:#B2D1E7;padding:10px;margin:10px">
<strong>{{franchise.franchise_name}}</strong> is in industry <strong>{{franchise.industry}}</strong> and has an initiation fee of <strong>${{franchise.initiation_fee}}</strong>
import os
import requests
import hubspot
from pprint import pprint
from hubspot.crm.objects import PublicObjectSearchRequest, ApiException
import json
def main(event):
headers = {'accept': 'application/json', 'content-type': "application/json"}
HAPI = os.getenv("HAPIKEY")
const request = require('request');
exports.main = (event, callback) => {
let industry = event.session.properties.CONTACT.industry.value.toLowerCase();
let budget = formatBudget(event.session.properties.CONTACT.franchise_budget.value);
console.log(industry)
console.log(budget.minBudget,budget.maxBudget)
let query = {
"operationName": "franchises",
@robertainslie
robertainslie / hs-operations hub-count-high-value-line-items.js
Created August 3, 2021 19:35
HubSpot Operations Hub - Count High Value Line Items.
const hubspot = require('@hubspot/api-client');
exports.main = (event, callback) => {
const hubspotClient = new hubspot.Client({
apiKey: process.env.HAPIKEY
});
//First, make a call to get deal associations
hubspotClient.crm.deals.associationsApi.getAll(event.object.objectId, 'line_item').then((results) => {

Use this code in HubSpot Operations Hub Custom Coded Action to dynamically set a Salesforce campaign member status, ideally upon conversion for any tracked contact that visits a page where the campaign ID is in the URL. This utilizes a combination of tools.

Note: it is recommended to use a third party integration (such as Integromat) to handle Salesforce authentication.

For a video overview of the solution, watch here: https://www.loom.com/embed/f328e82747764483b565a908d4a48dc1

@robertainslie
robertainslie / map-data-to-hubspot-form.js
Last active June 28, 2021 18:13
Sample script to map a json object of data to HubSpot form fields. The script takes 2 arguments: 1. An object of data and 2. An object of mappings. Given these two objects, the script will set these values into any fields on a form that match. This implementation fires change events on every field mapping due to HubSpot form rendering that uses …
function writeFormFieldData(mappingsObject, dataObject) {
var mappingsObject = mappingsObject
const changeEvent = new Event('change');
var mappedFieldsArray = Object.keys(mappingsObject);
var returnedDataArray = Object.keys(dataObject);
var fieldsToUpdate = mappedFieldsArray.filter(item => returnedDataArray.includes(item));
fieldsToUpdate.map(function(dataObjectFieldName) {
var hsFieldName = mappingsObject[dataObjectFieldName];
fieldToUpdate = document.querySelector(`[name="${hsFieldName}"]`);
if (fieldToUpdate == null) {