Advertisement
sumakaki

send form fetch

Mar 23rd, 2021 (edited)
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. let form = document.forms.article;
  2.  
  3. async function sendForm(url, body) {
  4.     try {
  5.         const response = await fetch(url,{
  6.             method: 'POST',
  7.             headers: {
  8.                 'Content-Type': 'application/json;charset=utf-8'
  9.             },
  10.             body: JSON.stringify(body)
  11.            
  12.         });
  13.         return await response.json();
  14.     } catch (error) {
  15.         console.error(error);
  16.     }
  17. }
  18.  
  19.  
  20. function renderArticles(data){
  21.   console.log(data.name)
  22. }
  23.  
  24. form.addEventListener('submit', async function(e){
  25.     e.preventDefault();
  26.    
  27.     const title = document.forms.article.title
  28.     const brand = document.forms.article.brand
  29.    
  30.  
  31.    const response = await sendForm('../test.php', {title, brand})
  32.    returnArticles(response)
  33. })
  34.  
  35.  
  36.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement