I have a requirement for my code to first go through a specific process and then extract the URL from the API for future use.
const apiKey = "_____________"
const file = document.getElementById("file")
const img = document.getElementById("img")
const url = document.getElementById("image_url")
file.addEventListener("change", ev => {
const formdata = new FormData()
formdata.append("file", ev.target.files[0])
formdata.append("upload_preset", apiKey)
fetch("https://api.cloudinary.com/v1_1/dj6n2zg0o/image/upload", {
method: "post",
body: formdata
}).then(data => data.json()).then(data => {
// Updates Image on HTML page
img.src = data.url
// Renders URL onto HTML
url.innerText = data.url
// Need to get image_url variable to newFormHandler function
return data.url
})
});
Once the image has been processed by the API, I then need to pass the URL to this form handler:
const newFormHandler = async (event) => {
event.preventDefault();
const name = document.querySelector('#name').value.trim();
const initial_price = document.querySelector('#initial_price').value.trim();
const description = document.querySelector('#description').value.trim();
if (name && initial_price && description) {
const response = await fetch(`/api/products`, {
method: 'POST',
body: JSON.stringify({ name, initial_price, description }),
headers: {
'Content-Type': 'application/json',
},
});
if (response.ok) {
document.location.replace('/');
} else {
alert('Failed to create project');
}
}
};
document
.querySelector('.new-product-form')
.addEventListener('submit', newFormHandler);
Any suggestions or guidance on this process would be highly valuable