APIs & Integrations

lloydsilver
Member

Include form fields as redirect URL parameters on an embedded form

SOLVE

I need to embed a HS form on an external (not CoS) website. And when the user submits the form, the redirect URL needs to include form fields as parameters.

Is this possible?

We figured out a way of doing this on a CoS landing page using a native HS form, but it was pretty tricky. In this case, I need to embed the form on an external page rather than use a CoS page.

What I’m trying to accomplish is capture the lead’s info (name, company, email) and then pass that info off to a scheduling app which can use parameters to pre-fill a scheduling form so the user doesn’t have to re-enter their info. And I want to do it through a HS form first so that we capture the lead and source information in HS. If we did it straight in the scheduling app then we could create a lead using Zapier but without Source info.

Every other form app I’ve used has been able to do this. Still surprised HS can’t do it off the shelf. But I hope someone has a creative workaround. Thanks.

2 Accepted solutions
derekcavaliero
Solution
Top Contributor | Diamond Partner
Top Contributor | Diamond Partner

Include form fields as redirect URL parameters on an embedded form

SOLVE

You could achieve this by using the onFormSubmit callback and switching the form to use an inline message instead of a redirect (explained below).

hbspt.forms.create({
    portalId: 'xxxxxxxx',
    formId: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx',
    inlineMessage: 'Your submit message here',
    onFormSubmit: function($form){
        setTimeout( function() {
            var formData = $form.serialize();
            window.location = "http://www.yoururl.com?" + formData;
        }, 250 ); // Redirects to url with query string data from form fields after 250 milliseconds.
    }
});

Because you have access to the jQuery $form object inside the onFormSubmit listener you can serialize the forms data and append it to a url to redirect to after the form is submitted. This only works if you have the inlineMessage set and disable the redirectUrl for the form.

See if that helps you out.

Derek Cavaliero
Director of Engineering

WebMechanix
www.webmechanix.com

View solution in original post

derekcavaliero
Solution
Top Contributor | Diamond Partner
Top Contributor | Diamond Partner

Include form fields as redirect URL parameters on an embedded form

SOLVE

@Albo 

 

Try setting your setTimeout to something higher than 100 milliseconds and see if that helps. I haven't had or seen this issue before - and in theory it shouldn't because the onFormSubmit is processed after the form is validated and request is sent. 

 

My theory is that if you redirect too quickly it may terminate the XHR request over to HubSpot's servers. I haven't actually tested this issue myself yet though - let me know what you find.

Derek Cavaliero
Director of Engineering

WebMechanix
www.webmechanix.com

View solution in original post

27 Replies 27
Teun
Recognized Expert | Diamond Partner
Recognized Expert | Diamond Partner

Include form fields as redirect URL parameters on an embedded form

SOLVE

For anyone searching for a solution where you can use the redirect settings from the form:

 

  window.addEventListener('message', event => {
    if (event.data.type === 'hsFormCallback' && event.data.eventName === 'onFormSubmitted') {
      const input = document.querySelector('select[name="input_name"]');
      const context = document.querySelector('input[name="hs_context"]');
      const contextObject = JSON.parse(context.value);
      const redirectUrl = contextObject.redirectUrl; // Retrieve the redirectUrl from the form settings

      if (input) {
        if (input.value && redirectUrl) {
          window.location.href = redirectUrl + `?input_name=${input.value}`;
        }
      }
    }
  });

 

 



Did my answer solve your issue? Help the community by marking it as the solution.
jkeough78
Contributor | Partner
Contributor | Partner

Include form fields as redirect URL parameters on an embedded form

SOLVE

@Teun ,  sorry, where do I put your code? Does that go in the <head> section? Do I still need to embed the form using HubSpot javascript embed code?

0 Upvotes
jc0
Member

Include form fields as redirect URL parameters on an embedded form

SOLVE

Alternatively, one can use onFormSubmitted:

  ...
  onFormSubmitted: function($form){
    window.location = "https://www.yoururl.com?" + $form.serialize();
  }
  ...
0 Upvotes
derekcavaliero
Top Contributor | Diamond Partner
Top Contributor | Diamond Partner

Include form fields as redirect URL parameters on an embedded form

SOLVE

@jc0 

Actually - you'll have problems with that - because HubSpot doesn't pass the $form argument to that callback like it does for onFormSubmit (this is very dumb and I had a lengthy chat w/ HubSpot support about it).

 

I would reccomend using onFormSubmit over onFormSubmitted - or if you plan on using onFormSubmitted - you'll need to "cache" the $form in a global variable which would mean setting it via onFormSubmit and then referencing it in the onFormSubmitted callback.

Derek Cavaliero
Director of Engineering

WebMechanix
www.webmechanix.com
0 Upvotes
andriigo
Contributor

Include form fields as redirect URL parameters on an embedded form

SOLVE

@derekcavaliero I tried this solution 

hbspt.forms.create({
    portalId: 'xxxxxxxx',
    formId: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx',
    inlineMessage: 'Your submit message here',
    onFormSubmit: function($form){
        setTimeout( function() {
            var formData = $form.serialize();
            window.location = "http://www.yoururl.com?" + formData;
        }, 250 ); // Redirects to url with query string data from form fields after 250 milliseconds.
    }
});

It displays thank you message, but doesn't redirect...

0 Upvotes
andriigo
Contributor

Include form fields as redirect URL parameters on an embedded form

SOLVE

@derekcavaliero This only works if you have the inlineMessage set and disable the redirectUrl for the form.
How to disable redirectUrl for the form?

0 Upvotes
Sheamus
Participant

Include form fields as redirect URL parameters on an embedded form

SOLVE

I built off of Derek's answer because I needed to use the built in landing pages, I was not using the form embed. The following worked for me.

<script>
  //code for redirecting to brew ninja signup flow after they enter their email
  $(document).ready(function() {
    setTimeout(function() {
      var form = $('[data-form-id=xxx-xxx-xx-your-form-id]');
      form.submit(function() {
        var email = $('[data-form-id=xxx-xxx-xx-your-form-id]').find('[name=email]').val();
        setTimeout(function() {
          window.location.href = 'https://yoursite.com?email=' + email;
        }, 500);
      });  
    }, 500);
  });
</script>
0 Upvotes
derekcavaliero
Top Contributor | Diamond Partner
Top Contributor | Diamond Partner

Include form fields as redirect URL parameters on an embedded form

SOLVE

@john_ascend @Trevor_Hatfield

Happy to help!

One thing I did not mention in my solution was to make 100% sure that you exclude any PII in the form data from being collected by Google Analytics.

Since we're talking about appending the data to the URL via a query string - GA will automatically capture that data inside its pageview reports. This means you'll likely need to add some custom logic around your tracking to make sure you adhere to the GA terms of use regarding collection of PII.

If you're using GTM (Google Tag Manager) to implement your web tracking (if you aren't I highly suggest you investigate) - this article is a great resource for understanding how to exclude data from being collected:

#GTMTips: Remove PII From Google Analytics Hits

Use customTask to automatically strip all personally identifiable information (PII) from requests sent to Google Analytics from your website.

Derek Cavaliero
Director of Engineering

WebMechanix
www.webmechanix.com
Jeromecollomb1
Member

Include form fields as redirect URL parameters on an embedded form

SOLVE

Hi @Lloyd_Silver,

I'm having the same issue, but on a COS landing page.
As you've apparently solved it before, any chance you can share the solution here?

Thanks a lot!

0 Upvotes
John
Top Contributor | Platinum Partner
Top Contributor | Platinum Partner

Include form fields as redirect URL parameters on an embedded form

SOLVE

Hey @Jeromecollomb, I know it's been a while since you asked your question, but I just posted an answer to another question that might help you out.

@derekcavaliero you are the man. This answer saved me a lot of time!



I like kudos almost as much as cake – a close second.

dimitreliasb
Contributor

Include form fields as redirect URL parameters on an embedded form

SOLVE

Hi @John  I came across this thread and we are having a very similar issue. I am passing just the email parameter to test from a hubspot form to a wordpress page (that includes the HubSpot tracking cod) . First line is the parameter they way i have it in the redirect and then the second is how it actually comes out. Any suggestions?

 

?email={{contact.email}}
email=%7B%7Bcontact.email%7D%7D

 

Basically I am trying to follor the directions in this article  but it does not seem to pass the parameter.

0 Upvotes
John
Top Contributor | Platinum Partner
Top Contributor | Platinum Partner

Include form fields as redirect URL parameters on an embedded form

SOLVE

well i'm years late (never saw this reply). The issue was that you were going from wordpress to hubspot and my solution only worked on a hubspot page



I like kudos almost as much as cake – a close second.

0 Upvotes
bryansteel
Participant

Include form fields as redirect URL parameters on an embedded form

SOLVE

YOU REALLY ARE THE MAN!@!!! This is it. 

robertainslie
HubSpot Employee
HubSpot Employee

Include form fields as redirect URL parameters on an embedded form

SOLVE

Hi @Lloyd_Silver,
Another way to do this is by re-running the hbspt.forms.create method of the embed code on change to each field and recreating the redirectUrl, appending each field. This changes the context and rebuilds the form on each call. @derekcavaliero 's method is probably better, but there are multiple ways to proceed.

That method looks like this:

hbspt.forms.create({
portalId: ‘[hub_id]’,
formId: ‘[form_guid]’,
redirectUrl:‘https://www.domain.com/page’,
target:’#target-node-for-form-build
});

In your JS, recall that entire method on change to each field, creating a redirectUrl like:
redirectUrl:‘https://www.domain.com/page?firstname=Lloyd’. Be sure to include the ‘target’ node so the embed code knows where to rebuilt the form each time.

Gthn
Participant

Include form fields as redirect URL parameters on an embedded form

SOLVE

Hi,

I've the same issue as the same @lloydsilver . The thing is I want to redirect users to a dynamic URL which already includes a "?".

 

Basically I want our users to fill a form with their website as one property to be redirected to a URL which include their website.

So if I a fill a form putting: http://www.mywebsite.com

People would be redirected to the following URL http://www.domain.com/simulate.php?url=http://www.mywebsite.com

 

1. I'm not sure to really understand how to use target:’#target-node-for-form-build’

2. I tried the dynamic query string (as i saw in HS knowledge) but it didn't work neither and i've the feeling it's because of the "?" which is inside the URL.

3. I tried the @derekcavaliero method but i didn't get how to use  window.location = "http://www.yoururl.com?" + formData;

 

Thanks in advance for your help

0 Upvotes
IsaacTakushi
HubSpot Employee
HubSpot Employee

Include form fields as redirect URL parameters on an embedded form

SOLVE

Hi, @Gthn.

 

Let's continue the conversation in this thread.

Isaac Takushi

Associate Certification Manager
0 Upvotes
derekcavaliero
Solution
Top Contributor | Diamond Partner
Top Contributor | Diamond Partner

Include form fields as redirect URL parameters on an embedded form

SOLVE

You could achieve this by using the onFormSubmit callback and switching the form to use an inline message instead of a redirect (explained below).

hbspt.forms.create({
    portalId: 'xxxxxxxx',
    formId: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx',
    inlineMessage: 'Your submit message here',
    onFormSubmit: function($form){
        setTimeout( function() {
            var formData = $form.serialize();
            window.location = "http://www.yoururl.com?" + formData;
        }, 250 ); // Redirects to url with query string data from form fields after 250 milliseconds.
    }
});

Because you have access to the jQuery $form object inside the onFormSubmit listener you can serialize the forms data and append it to a url to redirect to after the form is submitted. This only works if you have the inlineMessage set and disable the redirectUrl for the form.

See if that helps you out.

Derek Cavaliero
Director of Engineering

WebMechanix
www.webmechanix.com
Leigh_Oxley
Contributor

Include form fields as redirect URL parameters on an embedded form

SOLVE

Hi @derekcavaliero ! New Hubspot user here, and I'm a bit stuck, but it sounds like this code is pretty much exactly what I need. We're capturing some basic data in a Hubspot form (on a HS landing page) and then would like to redirect to a Calendly booking page with email and name embedded in the URL so Calendly can grab it.

 

I've tried just setting the form redirect link to be 

https://calendly.com/highwayed/info-session?firstname={{contact.firstname}}&lastname={{contact.lastname}}&email={{contact.email}}

(as this article states) but that doesn't seem to work, so I guess I need your code somewhere... the trouble is, I'm not sure where! Do I need a new custom module to add the javascript to the landing page? Would it go above or below the form itself? 

Appreciate any insight! Thank you for this thread!

0 Upvotes
derekcavaliero
Top Contributor | Diamond Partner
Top Contributor | Diamond Partner

Include form fields as redirect URL parameters on an embedded form

SOLVE

@Leigh_Oxley 

 

If you're using a hubspot hosted page with a default HubSpot form module, you'll need to use the global onFormSubmit callback as such:

 

<script>

function fieldsArrayToObject( fieldsArray ) {

    var valueCounter = {};
    var fields = {};

    for ( var i = 0; i < fieldsArray.length; i++ ) {

        var field = fieldsArray[i];
        
        if ( valueCounter.hasOwnProperty(field.name) ) {
            valueCounter[field.name]++;
        } else {
            valueCounter[field.name] = 1;
        }

    }

    for ( var i = 0; i < fieldsArray.length; i++ ) {

        var field = fieldsArray[i];

        if ( !fields.hasOwnProperty(field.name) ) {
            fields[field.name] = (valueCounter[field.name] > 1) ? [] : '';
        }

        if ( fields[field.name].constructor === Array ) {
            fields[field.name].push(field.value);
        } else {
            fields[field.name] = field.value;
        }

    }

    return fields;

}

window.addEventListener('message', function(event) {

    if (event.data.type !== 'hsFormCallback') return;

    if (event.data.eventName === 'onFormSubmit') {

        var fields = fieldsArrayToObject(event.data.data);
        var redirect = 'https://calendly.com/highwayed/info-session?firstname=' + fields.firstname + '&lastname=' + fields.lastname + '&email=' + fields.email;

        window.location.href = redirect;

    }

});
</script>

 

A few notes:

 

  • You need to make sure the form module on the page is set to show an inline message and not redirect when submitted. Otherwise this may not function properly
  • There is a utility method/function in the example above that formats the form field data from an array of objects into a single object of key:value pairs which is a much more sensible format (HubSpot doesn't format it this way naturally which is kind of a pain).
  • You would need to add this into the page settings in either the Header or Footer HTML under "Advanced Settings"

That should get you what you need. 

Derek Cavaliero
Director of Engineering

WebMechanix
www.webmechanix.com
0 Upvotes
dimitreliasb
Contributor

Include form fields as redirect URL parameters on an embedded form

SOLVE

@derekcavaliero I am trying to get this solution to work. Your snippet has come the closest to solving our issue however what happens with this code it redirects the page to a 404. Basically it pulls ALL the form data i think when we really only need to pull the email

So the URL string is full of parameters and at some point near the end of that screen it breaks the link.

The URL string looks like this:

?firstname=MYNAME&lastname=MYLASTNAME&email=MYEMAIL&company=&number_of_cnc_machines=0&zip=46268&do_you_currently_use_automation=No&hours_per_shift=&shifts_per_weekday=&shifts_per_weekend=&weeks_per_year=&operator_wages_per_hour=&operator_benefit=&system_cost=&hs_context=%7B%22rumScriptExecuteTime%22%3A1019.7899999911897%2C%22rumServiceResponseTime%22%3A1237.7850000048056%2C%22rumFormRenderTime%22%3A3.7949999677948654%2C%22rumTotalRenderTime%22%3A71.98499998776242%2C%22rumTotalRequestTime%22%3A216.79500001482666%2C%22lang%22%3A%22en%22%2C%22disableCookieSubmission%22%3Atrue%2C%22embedAtTimestamp%22%3A%221588874670525%22%2C%22formDefinitionUpdatedAt%22%3A%221588872328355%22%2C%22pageUrl%22%3A%22https%3A%2F%2Fprocobots.com%2Ftester%2F%22%2C%22pageTitle%22%3A%22Tester+-+ProCobots%22%2C%22source%22%3A%22FormsNext-static-3.480%22%2C%22timestamp%22%3A1588874670527%2C%22userAgent%22%3A%22Mozilla%2F5.0+(Windows+NT+10.0%3B+Win64%3B+x64)+AppleWebKit%2F537.36+(KHTML%2C+like+Gecko)+Chrome%2F81.0.4044.138+Safari%2F537.36%22%2C%22referrer%22%3A%22https%3A%2F%2Fprocobots.com%2Fwp-admin%2Fpost.php%3Fpost%3D2280%26action%3Dedit%22%2C%22originalEmbedContext%22%3A%7B%22portalId%22%3A%22209468%22%2C%22formId%22%3A%2296085b29-963b-4ce5-9a65-4f9f3046ee1b%22%2C%22inlineMessage%22%3Atrue%2C%22target%22%3A%22%23hbspt-form-1588874670572-8723872668%22%2C%22hutk%22%3A%22f6a5fcd85d55f675630d59b5873faf7c%22%2C%22shellId%22%3A0%2C%22shell%22%3Atrue%2C%22pageUrl%22%3A%22https%3A%2F%2Fprocobots.com%2Ftester%2F%22%2C%22pageTitle%22%3A%22Tester
0 Upvotes