Skip to content

Instantly share code, notes, and snippets.

@Sammuel09
Created October 15, 2018 17:17
Show Gist options
  • Save Sammuel09/5940587365f6e9d103e5637dd1b83808 to your computer and use it in GitHub Desktop.
Save Sammuel09/5940587365f6e9d103e5637dd1b83808 to your computer and use it in GitHub Desktop.
This gist describe my code for post menu using cloudinary.
const form = document.querySelector('form');
const name = document.querySelector('#name');
const imageurl = document.querySelector('#image');
const price = document.querySelector('#price');
const postMenuBtn = document.querySelector('#postMenuBtn');
const successMsg = document.querySelector('#successMsg');
const CLOUDINARY_URL = 'https://api.cloudinary.com/v1_1/dx8yi1fsi/image/upload';
const CLOUDINARY_UPLOAD_PRESET = 'ruamt9zr';
const handleResponse = response => response.blob()
.then((blob) => {
if (response.ok) {
return blob;
} if (!response.ok) {
throw new Error(JSON.stringify(blob));
}
});
imageurl.addEventListener('change', (event) => {
const file = event.target.files[0];
console.log (file);
const formData = new FormData();
formData.append('file', file);
formData.append('upload_preset', 'savri87we342');
fetch(CLOUDINARY_URL, {
method: 'POST',
body: formData,
})
.then(handleResponse)
.then((res) => {
console.log(JSON.stringify(res));
})
.catch((res) => {
console.log(res);
});
});
const sendFormData = () => {
fetch('https://sammie-fast-food-fast.herokuapp.com/api/v1/menu', {
method: 'post',
headers: {
'content-type': 'application/json',
},
body: JSON.stringify({
name: document.querySelector('#name').value,
price: document.querySelector('#price').value,
}),
})
.then(handleResponse)
.then((response) => {
localStorage.setItem('name', `${response.data.rows[0].name}`);
localStorage.setItem('imageurl', `${response.data.rows[0].imageurl}`);
localStorage.setItem('price', `${response.data.rows[0].price}`);
successMsg.innerHTML = response.message;
})
.catch((error) => {
console.log(error);
});
};
postMenuBtn.addEventListener('click', (event) => {
event.preventDefault();
sendFormData();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment