APIs & Integrations

lloydsilver
Membro

Include form fields as redirect URL parameters on an embedded form

resolver

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.

3 Solução aceitas
derekcavaliero
Solução
Top colaborador(a) | Parceiro Diamante
Top colaborador(a) | Parceiro Diamante

Include form fields as redirect URL parameters on an embedded form

resolver

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

Exibir solução no post original

derekcavaliero
Solução
Top colaborador(a) | Parceiro Diamante
Top colaborador(a) | Parceiro Diamante

Include form fields as redirect URL parameters on an embedded form

resolver

@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

Exibir solução no post original

Teun
Solução
Especialista reconhecido(a) | Parceiro Diamante
Especialista reconhecido(a) | Parceiro Diamante

Include form fields as redirect URL parameters on an embedded form

resolver

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}`;
        }
      }
    }
  });

 

 



Learn more about HubSpot by following me on LinkedIn or YouTube

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


Exibir solução no post original

45 Respostas 45
Teun
Solução
Especialista reconhecido(a) | Parceiro Diamante
Especialista reconhecido(a) | Parceiro Diamante

Include form fields as redirect URL parameters on an embedded form

resolver

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}`;
        }
      }
    }
  });

 

 



Learn more about HubSpot by following me on LinkedIn or YouTube

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


HeatherT
Membro

Include form fields as redirect URL parameters on an embedded form

resolver

I do not have the redirectUrl as part of the form's hs_context value.  Do you know if this has changed, or if there is something I need to do in order to have it as part of the value?

 

** Update **

I found where I could get the redirectUrl off of the event data.  Thought I'd share this script.  It goes through the form and appends all non-hidden form fields as query params to the redirect url. Thought it might be useful for someone else running into the same issue I did.

 

window.addEventListener('message', (event) => {
    if (event.data.type === 'hsFormCallback') {
        if (event.data.eventName === 'onFormSubmitted') {
            if (event?.data?.data?.redirectUrl && event?.data?.id) {
                const redirectUrl = new URL(event.data.data.redirectUrl);
                const formId = `hsForm_${event.data.id}`;
                const form = document.getElementById(formId);
                if (form) {
                    Array.from(form.elements)
                        .filter(
                            (input) =>
                                input.type !== 'hidden' &&
                                input.type !== 'submit',
                        )
                        .forEach((field) =>
                            redirectUrl.searchParams.append(
                                field.name,
                                field.value,
                            ),
                        );

                    window.location = redirectUrl.toString();
                }
            }
        }
    }
});

 

GMirazchiev3
Participante

Include form fields as redirect URL parameters on an embedded form

resolver

@HeatherT thanks for sharing your solution - where would add the above script? 

 

I've been testing the solutions above and I've created a simple HubSpot Form embedded on our website that redirects to a HubSpot Scheduling page on successful completion.

 

https://chattermill.com/new-page (pass: 1234567)

 

However, I can't get the values for email, first name and last name to append to the url.

 

I have no technical expertise of HTML or scripts, hence why I'm a bit lost.

 

Thanks in advance for any help!

0 Avaliação positiva
HeatherT
Membro

Include form fields as redirect URL parameters on an embedded form

resolver

@GMirazchiev3 

I took a quick look. For some reason the value for "redirectUrl" is blank.

 

I'm not sure why the value for "redirectUrl" is blank.  For my setup - I've added the redirect url in the form under "What should happen if a visitor submits this form" > where I've selected an "External link..."  

 

I'm not sure if Hubspot does something different if it is an internal link???

 

To help troubleshoot you can add a bunch of console logs to see what is going on 🙂 Since the page is redirecting you'll lose the console.logs. But in chrome developer tools you can go to the settings and select "preserve log" - so you can continue to see the logs after you've redircted to the new page.

 

And just place the script in the head or in the body within <script></script> tags. It doesn't matter where

 

Here's the script with some console logs added

 

 

window.addEventListener('message', (event) => {
    if (event.data.type === 'hsFormCallback') {
        console.log(event.data.eventName);
        if (event.data.eventName === 'onFormSubmitted') {
            for (const [key, value] of Object.entries(event?.data?.data)) {
               console.log(`${key}: ${value}`);
            }
            console.log(`REDIRECT URL: ${event?.data?.data?.redirectUrl}`);

            if (event?.data?.data?.redirectUrl && event?.data?.id) {
                const redirectUrl = new URL(event.data.data.redirectUrl);
                const formId = `hsForm_${event.data.id}`;
                const form = document.getElementById(formId);
                if (form) {
                    Array.from(form.elements)
                        .filter(
                            (input) =>
                                input.type !== 'hidden' &&
                                input.type !== 'submit',
                        )
                        .forEach((field) =>
                            redirectUrl.searchParams.append(
                                field.name,
                                field.value,
                            ),
                        );
                    window.location = redirectUrl.toString();
                }
            } else {console.log('Do not have a redirect url or id');}
        }
    }
});

 

 

0 Avaliação positiva
GMirazchiev3
Participante

Include form fields as redirect URL parameters on an embedded form

resolver

@HeatherT thanks for this - I originally had set the form settings to display an inline message and added the redirecturl in the embed code (as someone in this thread suggested).

 

I have now updated the form and done the same as you: I've added the redirect url in the form under "What should happen if a visitor submits this form" > where I've selected an "External link..." and added the url there.

 

I've also added the code you sent over to the page - thanks for sharing it.

 

However, the form data is still not appended to the redirect url, but instead a submissionID is appended (?submissionGuid=2e7ac3a9-0a94-4c79-8530-18e5f6a1e405).

 

Do you have any idea why this is?

 

Thanks again for your help so far.

0 Avaliação positiva
Jaycee_Lewis
Gerente da Comunidade
Gerente da Comunidade

Include form fields as redirect URL parameters on an embedded form

resolver

Hey, @HeatherT! Thank you very much for sharing what worked for you 🙌 — Jaycee

linkedin

Jaycee Lewis

Developer Community Manager

Community | HubSpot

0 Avaliação positiva
seanm914
Participante

Include form fields as redirect URL parameters on an embedded form

resolver

Hi Teun - where do I put this code?

 

0 Avaliação positiva
jkeough78
Colaborador(a) | Parceiro
Colaborador(a) | Parceiro

Include form fields as redirect URL parameters on an embedded form

resolver

@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 Avaliação positiva
seanm914
Participante

Include form fields as redirect URL parameters on an embedded form

resolver

were you able to figure this out?

0 Avaliação positiva
jc0
Membro

Include form fields as redirect URL parameters on an embedded form

resolver

Alternatively, one can use onFormSubmitted:

  ...
  onFormSubmitted: function($form){
    window.location = "https://www.yoururl.com?" + $form.serialize();
  }
  ...
0 Avaliação positiva
derekcavaliero
Top colaborador(a) | Parceiro Diamante
Top colaborador(a) | Parceiro Diamante

Include form fields as redirect URL parameters on an embedded form

resolver

@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
andriigo
Colaborador(a)

Include form fields as redirect URL parameters on an embedded form

resolver

@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 Avaliação positiva
derekcavaliero
Top colaborador(a) | Parceiro Diamante
Top colaborador(a) | Parceiro Diamante

Include form fields as redirect URL parameters on an embedded form

resolver

@andriigo my appologies, I made a mistake the code I provided, it should be:

window.location.replace("http://www.yoururl.com?" + formData);

instead of:

window.location = "http://www.yoururl.com?" + formData;
Derek Cavaliero
Director of Engineering

WebMechanix
www.webmechanix.com
0 Avaliação positiva
GMirazchiev3
Participante

Include form fields as redirect URL parameters on an embedded form

resolver

@derekcavaliero I see you have been helping out people with this for years, so you migth be able to help!

I'm trying to achieve what other people here are - appending utm values upon form submission so people don't have to input their info again. 

I've created this test page here - https://chattermill.webflow.io/new-page (pass: 1234567) and embedded a test form.

Ideal state would be that on successfull form submission, users are redirected to (https://meetings.chattermill.com/meetings/gmirazchiev/meetings-scheduler-for-demopricing) and values for email, first name and last name are appended to the URL.

I've tried several methods and some of the code snippets here, but can't get it to work.

The redirect element works and redirects to the correct url, but the form data isn't appended to the URL

The embed snippet I've used is:

hbspt.forms.create({
region: "na1",
portalId: "613982",
formId: "eb6ca632-e7fb-424c-ba32-ac9184679fb2",
inlineMessage: 'Your submit message here',
cssClass: "hs-s-contact-form",
onFormSubmitted: function($form){
setTimeout( function() {
var formData = $form.serialize();
window.location.replace("https://meetings.chattermill.com/meetings/gmirazchiev/meetings-scheduler-for-demopricing?" + formData);
}, 250 ); // Redirects to url with query string data from form fields after 250 milliseconds.
}
});

Do you have any idea what I'm doing wrong?

Thanks


0 Avaliação positiva
seanm914
Participante

Include form fields as redirect URL parameters on an embedded form

resolver

Hi @derekcavaliero  - when i embed this code onto my site (after adjusting the code with my portal ID, etc, the form doesn't even appear on my page. Any advice?

0 Avaliação positiva
derekcavaliero
Top colaborador(a) | Parceiro Diamante
Top colaborador(a) | Parceiro Diamante

Include form fields as redirect URL parameters on an embedded form

resolver

Are you seeing any errors in the dev tools console?

Derek Cavaliero
Director of Engineering

WebMechanix
www.webmechanix.com
Jaycee_Lewis
Gerente da Comunidade
Gerente da Comunidade

Include form fields as redirect URL parameters on an embedded form

resolver

Hey, @derekcavaliero thanks for continuing to try to support this thread. You rock 🙌 — Jaycee

linkedin

Jaycee Lewis

Developer Community Manager

Community | HubSpot

0 Avaliação positiva
andriigo
Colaborador(a)

Include form fields as redirect URL parameters on an embedded form

resolver

@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 Avaliação positiva
derekcavaliero
Top colaborador(a) | Parceiro Diamante
Top colaborador(a) | Parceiro Diamante

Include form fields as redirect URL parameters on an embedded form

resolver

Inside the form settings in hubspot, or you can set it explicitly in the embed code with the inlineMessage option. 

Derek Cavaliero
Director of Engineering

WebMechanix
www.webmechanix.com
0 Avaliação positiva
Sheamus
Participante

Include form fields as redirect URL parameters on an embedded form

resolver

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>