Integrating with External APIs
Describes fetching data from an external API to pre-populate form fields and submitting form data to an API endpoint.
// Define the URL for the external API
const apiURL = 'https://external-api.com/data';
// Function to fetch data and populate the form fields
async function populateFormWithExternalData() {
try {
const response = await fetch(apiURL);
const data = await response.json();
// Assuming data object has fields that match form field IDs
document.getElementById('name').value = data.name;
document.getElementById('email').value = data.email;
} catch (error) {
console.error('Failed to fetch data:', error);
}
}
// Call the function to populate the form
populateFormWithExternalData();
This code snippet fetches data from an external API and populates form fields with the retrieved data. It makes a GET request to the API, waits for the response, and then populates form fields with specific data points from the response.
// Define the URL for the API endpoint
const submitApiUrl = 'https://external-api.com/submit';
// Function to submit form data to an external API
async function submitFormData(event) {
event.preventDefault();
const formData = {
name: document.getElementById('name').value,
email: document.getElementById('email').value
};
try {
const response = await fetch(submitApiUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(formData)
});
const result = await response.json();
console.log('Form submitted successfully:', result);
} catch (error) {
console.error('Failed to submit form:', error);
}
}
// Add event listener to the form submit button
const submitButton = document.getElementById('submit-button');
submitButton.addEventListener('click', submitFormData);
This snippet captures the submission of a form and sends the form data as a JSON object to an external API using a POST request. It attaches an event listener to the submit button, gathers form data into an object, then sends it to the API.