Here’s a detailed guide on making a POST call in JavaScript to Telivy backend form input when a submit button is clicked on your own form:
Set Up The HTML Form
Create a form with the method attribute set to POST and a submit button.
Attach A JavaScript Event Listener
Use addEventListener to listen for the submit event on the form.
Gather Form Data
Use FormData to construct a data object from the form’s input fields. Add the agentId or UTM Source fields to the form data if necessary.
Before you proceed any further, please make sure that the following validations to the data are passed:
Ensure the email has an ”@.”
Ensure the email has an ”@.”
Ensure the domain is valid. The following examples are valid domains:
https://www.cleansolar.com
www.cleansolar.com
cleansolar.com
https://www.cleansolar.com/
www.cleansolar.com/
cleansolar.com/
Send The POST Request
Use the fetch API to send the POST request.
Here’s the full example:
<form id="myForm" method="POST">
<input type="text" name="organizationName" placeholder="Enter the name of your business">
<input type="email" name="contactEmail" placeholder="Enter your email">
<input type="text" name="domain" placeholder="Enter your website domain">
<button type="submit">Submit</button>
</form>
<script>
const form = document.getElementById("myForm");
form.addEventListener("submit", (event) => {
event.preventDefault();
const formData = new FormData(form);
// Replace with your actual Agent ID.
formData.append("agentId", "your-agent-id-here");
// Read next article to learn about utm source tracking
formData.append("utmSource", "custom-form");
const dataObj = {};
formData.forEach(function(value, key){
dataObj[key] = value;
});
fetch("https://api-v1.telivy.com/api/v1/applications/public", {
method: "POST",
body: JSON.stringify(dataObj),
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
})
.then(data => {
console.log(data);
})
.catch(error => {
console.error(error);
});
});
</script>