Custom form submit handler

The Send2CRM client can handle form submissions automatically, with no additional coding required. For those who need finer control over their forms, Send2CRM functions can be used in a custom submit handler.

<form method="post" id="example_form"> <label for="firstName">First name</label> <input type="text" name="firstName" /> <label for="lastName">Last name</label> <input type="text" name="lastName" required /> <label for="email">Email</label> <input type="email" name="email" required /> <label for="company">Company</label> <input type="text" name="company" required /> <button type="submit">Submit</button> </form>

The form above can be handled with the following JavaScript.

document.queryLocator('#example_form').addEventListener('submit', (event) => { let form = event.target; // Build an object with form values. let formValues = { first_name: form.querySelector('[name="firstName"]').value, last_name: form.querySelector('[name="lastName"]').value, email_address: form.querySelector('[name="email"]').value, organization: form.querySelector('[name="company"]').value, }; // Alternatively we could use a FormData object to iterate all values: // https://developer.mozilla.org/en-US/docs/Web/API/FormData // Optional: add UTM parameters if enabled and present. send2crm.util.extend(formValues, send2crm.util.getUtmParams()); // Perform any pre-processing tasks required, perhaps additional validation. // Send to Send2CRM service. send2crm.forms.send('custom_form_id', formValues) .then(response => { // Success. // Perform any post-processing tasks required, save to additional locations? window.location.href = '/thankyou'; }) .catch(error => { // Failed. Inform the user, perform any additional processing required. console.log(error.message); alert('Form submission failed.'); }); });