APIs & Integrations

lloydsilver
Member

Include URL Parameters In Redirect URL After Form Submission

HubSpot cannot natively add any parameters to a redirect URL that the user is sent to after submitting a form (sadly). So we created some javascript that essentially waits until the user’s contact record gets populated with data and then redirects to the url adding the contact info as needed.

It works, but sometimes we are getting stuck in a loop where it’s not redirecting (presumably because it’s still waiting for the contact info to get populated).

This is being used on a HS landing page with a native form. It’s being added in the sourcecode of the submission message. Again, it does work. It just sometimes stalls out in a loop waiting for the user data to populate.

Here’s the code we are using. I’m wondering if anybody has suggestions on improving this:

<script>// <![CDATA[
$(function() {
    var personalizedDiv = $("#personalized-div");
    var personalizedInfo = {};
    personalizedInfo['firstname'] = (personalizedDiv.data("firstname"))?personalizedDiv.data("firstname"):"";
    personalizedInfo['lastname'] = (personalizedDiv.data("lastname"))?personalizedDiv.data("lastname"):"";
    personalizedInfo['company'] = (personalizedDiv.data("company"))?personalizedDiv.data("company"):"";
    personalizedInfo['email'] = (personalizedDiv.data("email"))?personalizedDiv.data("email"):"";
    personalizedInfo['phone'] = (personalizedDiv.data("phone"))?personalizedDiv.data("phone"):"";
    
    
    
    var err = 0;
    for (var val in personalizedInfo) {
        console.log(personalizedInfo[val]);
        if(personalizedInfo[val].length == 0) {
            err++;
        }
    }
    
    
    if(err == 0) {
        window.location.href = "http://site.com/schedule-a-tour?name="+personalizedInfo['firstname'] +" "+ personalizedInfo['lastname']+"&email="+personalizedInfo['email']+"&company="+personalizedInfo['company']+"&phone="+personalizedInfo['phone']+"&skip=1";
    } else {
        setTimeout(function() { 
            location.reload();
        }, 6000);
    }
});
// ]]></script>
<div id="personalized-div" data-firstname="{{contact.firstname}}" data-lastname="{{contact.lastname}}" data-email="{{contact.email}}" data-company="{{contact.company}}" data-phone="{{contact.phone}}">&nbsp;</div>
Please wait while we redirect you to our scheduling system ...
0 Upvotes
6 Replies 6
Teun
Recognized Expert | Diamond Partner
Recognized Expert | Diamond Partner

Include URL Parameters In Redirect URL After Form Submission

For anyone who wants to use the Redirect URL from the form settings:

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.


MatthieuBRG
Participant

Include URL Parameters In Redirect URL After Form Submission

Hi Teun, 

 

not dev here, what does this allow to do exactly? 

 

I'm looking to add URL parameters (email) to the URL where I redirect users after filling out Hubspot form. 

 

Which solution should I go for? Yours, lloydsilver original post or Xflxium's cookie one 

 

And how to implement your solution if that's the preferred one? 

 

Thanks a lot

0 Upvotes
MdFarhan
Member

Include URL Parameters In Redirect URL After Form Submission

@Xfixium Need help passing specific fields from the form as URL query parameters

Hey,

I found your solution helpful but not sure how to implement it. We want to pass specific fields from the form as URL query parameters. Can you help?

0 Upvotes
AlphaDave
Participant

Include URL Parameters In Redirect URL After Form Submission

Thanks Xflxium!! - your solution worked like a champ. (It's a shame HubSpot does allow this functionality by itself.)

0 Upvotes
Xfixium
Member

Include URL Parameters In Redirect URL After Form Submission

This a way that I did it, it’s cookie based and basically works by setting the HubSpot page to redirect into itself. So when the submit button for a form is clicked, the code gets all the form field data, and appends it to the desired redirect url. It saves this url in a cookie. Then when the page redirects into itself, if the cookie is not empty, it redirects to the url saved in the cookie.

function getCookie(cname) {
   var name = cname + "=";
   var decodedCookie = decodeURIComponent(document.cookie);
   var ca = decodedCookie.split(';');
   for(var i = 0; i <ca.length; i++) {
       var c = ca[i];
       while (c.charAt(0) == ' ') {
           c = c.substring(1);
       }
       if (c.indexOf(name) == 0) {
           return c.substring(name.length, c.length);
       }
   }
   return "";
}

var url = getCookie("UrlWithParameters");
if(url != "") {
   javascript:void(document.cookie = "UrlWithParameters=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;");
   window.location = url;
}

$(function () {
   $(window).load(function(){
       $("form.hs-form").live("submit", function (e) {
           var appendFields = function (url, values) {
               var data = {};
               $.each(values, function (i, item) {
                   if (item.name !== "hs_context") {
                       data[item.name] = item.value;
                   }
               });
               
               if (url.match(/\?/)) {
                   return url + "&" + encodeURIComponent($.param(data));
               } else {
                   return url + "?" + encodeURIComponent($.param(data));
               }
           };
           
           var $form = $(this);
           var apiUrl = $form.attr("action");
           var $hsContext = $("input[name='hs_context']", $form);
           var hsContext = JSON.parse($hsContext.val());
           var redirect = 'https://your_base_url.com';
           hsContext.redirectUrl = appendFields(redirect, $form.serializeArray());
           $hsContext.val(JSON.stringify(hsContext));
           javascript:void(document.cookie="UrlWithParameters=" + hsContext.redirectUrl);
       });
   });
});
djpritchett
Member

Include URL Parameters In Redirect URL After Form Submission

Xfixium,

I created a forum account just to say thanks… saved me hours.