Blog>
Snippets

Handling Form Submission and API Integration

Provide an example of handling form submissions, including how to integrate with a third-party API using fetch API for data submission.
async function handleSubmit(event) {
  event.preventDefault();
  const formData = new FormData(event.target);
  const data = Object.fromEntries(formData.entries());
  // Replace YOUR_API_ENDPOINT with the actual endpoint
  const url = 'YOUR_API_ENDPOINT';

  try {
    const response = await fetch(url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(data),
    });

    if (!response.ok) {
      throw new Error(`Request failed: ${response.status}`);
    }

    const result = await response.json();
    alert('Form submitted successfully.');
    console.log('Server response:', result);
  } catch (error) {
    console.error('Submission error:', error);
    alert('Failed to submit the form.');
  }
}
This function handles the form submission. It prevents the default form submission process, gathers the form data, and sends it as a JSON object to a specified API endpoint using the fetch API with a POST request. It then handles the server's response or logs an error if the request fails.
// In your HTML form, ensure to call handleSubmit on form submit
// <form id='myForm' onsubmit='handleSubmit(event)'>
// Add form fields inside this form tag
// </form>

document.getElementById('myForm').addEventListener('submit', handleSubmit);
This code snippet shows how to attach the handleSubmit function to a form's submit event using an event listener. Ensure the form has an id of 'myForm' and include your form fields inside this form tag.