How can I create a link from a Webflow form to an API using custom code?

Published on
September 22, 2023

To create a link from a Webflow form to an API using custom code, follow these steps:

  1. Set up your API endpoint: First, you need to have an API endpoint or URL where you want to send the form data. This can be a custom-built API or a third-party service like Zapier or Integromat. Make sure you have the necessary authentication credentials or API key to access the endpoint.

  2. Create the Webflow form: In the Webflow Designer, drag and drop a form element onto your page or use an existing form. Add the necessary form fields like name, email, message, etc. Make sure to give each form field a unique name attribute.

  3. Add custom code: In the Webflow Designer, click on the page where your form is located and open the "Page Settings" panel on the right sidebar. Scroll down to the "Custom Code" section and click on the "Head Code" tab.

  4. Write the custom code: In the head code section, write JavaScript code to handle the form submission and send data to the API. You can use the addEventListener method to listen for the form submission event.

Example code:

<script>document.addEventListener("DOMContentLoaded", function() {  var form = document.getElementById("my-form");  form.addEventListener("submit", function(e) {    e.preventDefault(); // Prevent default form submission    // Get form data    var formData = new FormData(form);    // Make a POST request to your API endpoint    fetch("https://api.example.com/submit", {      method: "POST",      body: formData    })    .then(function(response) {      if (response.ok) {        // Handle successful response        console.log("Form data submitted successfully!");      } else {        // Handle error response        console.error("Error submitting form data:", response.status);      }    })    .catch(function(error) {      // Handle network error      console.error("Network error:", error);    });  });});</script>
  1. Replace my-form with your form ID: In the JavaScript code, replace "my-form" with the actual ID of your form element. This ID can be found in the Webflow Designer under the "Settings" tab of the form element.

  2. Publish your site: Once you have added the custom code, save and publish your site for the changes to take effect. Your Webflow form will now be linked to the API, and form submissions will be sent to the specified endpoint.

Additional Resources:

Q&A:

  1. How do I create a Webflow form?
  2. How can I customize the appearance of a Webflow form?
  3. What are some popular API integrations with Webflow?