APIs & Integrations

Anshul1
Member

How to return an error in custom hubspot.create.form script

I'm using the following code in hbspt.forms.create to validate the presence of user in the database before adding him to the target website and hubspot database. If the user is already present in the database of target website, then HS script should not get executed further and return an error i.e., user already present. If the user is a new user, based on the validation below, he would be added to the HS database of the client. I'm not sure how to return an error to the calling function so that the HS script stops executing and returns an error to the user. With the script below, the user gets added to HS when the custom script returns false. This should not happen. Any suggestion and improvements to the code below would be appreciated.

"script charset="utf-8" type="text/javascript" src="//js.hsforms.net/forms/v2-legacy.js">

hbspt.forms.create({ portalId: "4216614", formId: "5558a76c-18ab-40d0-ba8a-275331e06357", css: "", onFormSubmit: function ($form) { var first_name = document.getElementById('firstname-5558a76c-18ab-40d0-ba8a-275331e06357').value; var last_name = document.getElementById('lastname-5558a76c-18ab-40d0-ba8a-275331e06357').value; var full_name = first_name.concat(last_name); var email = document.getElementById('email-5558a76c-18ab-40d0-ba8a-275331e06357').value; var parameters = { name: full_name, email: email }; var xhttp = new XMLHttpRequest(); xhttp.open("POST", "https://api.trustwire.com/_api/thirdparty/register", false); xhttp.setRequestHeader("Content-type", "application/json"); xhttp.send(JSON.stringify(parameters)); var response = JSON.parse(xhttp.responseText); if (response.error != undefined) { this.error("Invalid"); return false; } return true; } }); </script"
0 Upvotes
1 Reply 1
salty_stephen
Contributor | Elite Partner
Contributor | Elite Partner

How to return an error in custom hubspot.create.form script

Hi @Anshul,

If you check out this post I made a while ago, it uses the bubbling properties of the DOM to allow you to attach events to the submit button.

If you add in a e.preventDefautl() instead of return false, this should work as you intend.