Skip to content

Instantly share code, notes, and snippets.

@hijonathan
Last active August 1, 2023 19:14
Show Gist options
  • Star 29 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save hijonathan/9898070 to your computer and use it in GitHub Desktop.
Save hijonathan/9898070 to your computer and use it in GitHub Desktop.
Submit a HubSpot form with AJAX without redirecting the user.
<form class='form-inline' id='my-custom-form'>
<div class="form-group">
<input type='email' class='form-control' placeholder='Your email address' required>
</div>
<button class="btn btn-primary" type='submit'>Sign up</button>
</form>
<!-- Actual form that gets submitted to HubSpot -->
<div class="hidden" id='hubspot-form'>
<script charset="utf-8" src="//js.hsforms.net/forms/current.js"></script>
<script>
hbspt.forms.create({
portalId: 'YOUR_PORTAL_ID',
formId: 'TARGET_FORM_ID',
onFormReady: function($form) {
$form.attr('target', 'hubspot-iframe');
}
});
</script>
<!-- iFrame that data will get submitted to. This hack stops the page redirect. -->
<iframe name="hubspot-iframe" id="hubspot-iframe"></iframe>
</div>
// Send form data to HubSpot from the client.
function submitToHubSpot(data) {
var $form = $('#hubspot-form form'),
k;
// Loop through each value and find a matching input.
// NOTE: Doesn't support checkbox/radio.
for (k in data) {
$form.find("input[name='" + k + "']").val(data[k]);
}
$form.submit();
}
// Here's how you'd use this.
$('#my-custom-form').on('submit', function() {
var formData = {};
$(this).serializeArray().forEach(function(data) {
formData[data.name] = data.value;
});
submitToHubSpot(formData);
// We sent the data. Now do whatever else you want.
alert('Gee, thanks Jonathan! Now I can focus on onboarding my customers with Appcues!');
window.location.href = 'http://appcues.com';
})
@SeanJM
Copy link

SeanJM commented Jun 13, 2014

Thanks for the snippet!

@hijonathan
Copy link
Author

Glad I could help @SeanJM :shipit:

@chaoslogick
Copy link

This works, except it does not send some crucial HubSpot cookie data through the iframe on the submission. Currently working through this and will report back if/when it gets sorted.

@jamesbebbington
Copy link

@michaelperrygoodman would you be so kind as to explain what cookie data is getting lost. Did you have any luck sorting it? Thanks.

@tbarn
Copy link

tbarn commented Jan 8, 2015

Seconding what @Fractious said. Any details you could add @michaelperrygoodman?

@andrewrogersroi
Copy link

Thanks for this snippet. I'll be using it for those uniquely styled forms my designer loves to have on the home page:)

@tin-lam
Copy link

tin-lam commented Mar 17, 2015

the submit button generated by the hubspot form apparently gather and load more page/context info to the form. so simply mapping the values to the fields then submitting the form would be missing them out. fix is very simple thou... instead of $form.submit(), do $("form input:submit").trigger("click"), that's jquery syntax. this will simulate the click event on the submit button, then it will do its thing, everything lines up :-)

@hijonathan
Copy link
Author

Aw man, totally missed these notifications. Sounds like @tin-lam's suggestion fixes the issue @michaelperrygoodman and @tbarn were seeing, though I haven't verified it myself.

@nicholashead
Copy link

Thanks! This worked great.

@jake-wells
Copy link

If you need to support checkboxes/radio buttons, I found this from Hubspot and it works:

In order to use jQuery to manipulate the values of form inputs using .val() or .prop(), you must trigger a change event using change() or trigger('change') for the change to properly register.

Since HubSpot forms are rendered after the DOM builds, you must either trigger the manipulation after the window loads, or modify the embed to use the onFormReady parameter.

$('input[value="checkbox_1"]').prop('checked', true).change();

@stefenphelps
Copy link

stefenphelps commented Aug 24, 2016

Thanks for sharing!

@zackphilipps
Copy link

zackphilipps commented Sep 25, 2017

This is still an issue with Hubspot! We are continuing to monitor the solution we went with, but so far, no issues.

Basically, I used the iframe/target method presented above, but with no secondary form and no submitjacking. (As far as I can tell there actually isn't a true submitjacking going on above either, i.e. there is no preventDefault().)

This works because the Hubspot response/redirect is happening within the frame, behind the scenes, instead of on the page itself.

On submit, using the onFormSubmit method provided by Hubspot, we are simply hiding the form and showing a custom form flip.

So, the full code looks like this:

<div class="form-wrapper">
  <div class="hbspt-form">
    <!--[if lte IE 8]>
    <script charset="utf-8" type="text/javascript" src="//js.hsforms.net/forms/v2-legacy.js"></script>
    <![endif]-->
    <script charset="utf-8" type="text/javascript" src="//js.hsforms.net/forms/v2.js"></script>
    <script>
    hbspt.forms.create({ 
      css: '',
      portalId: 'xxxxxx',
      formId: 'xxxxxx',
      target: '.hbspt-form',
      onFormReady: function($form) {
        $form.attr('target', 'hubspot-iframe');
      },
      onFormSubmit: function($form) {
        jQuery('.form-wrapper .hbspt-form').hide();
        jQuery('.form-confirmation').show();
      }
    });
    </script>
  </div>
  <iframe class="hidden" name="hubspot-iframe" id="hubspot-iframe"></iframe>
  <div class="form-confirmation">
    <div class="form-confirmation-inner">
      <!-- custom form flip here -->
    </div>
  </div>
</div>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment