Skip to content

Instantly share code, notes, and snippets.

@olygood
Last active February 24, 2021 11:18
Show Gist options
  • Save olygood/573f622bc6f8c8e7731bde5a15d1a665 to your computer and use it in GitHub Desktop.
Save olygood/573f622bc6f8c8e7731bde5a15d1a665 to your computer and use it in GitHub Desktop.
fetch async/await formulaire avec reponse du server api
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=Mulish:wght@300;400;700&display=swap" rel="stylesheet">
<title>formulaire</title>
</head>
<body>
<div class="container">
<header>
<a class="header-brand" href="./index.html">Blog</a>
<ul>
<li>
<a href="./index.html" class="header-nav">Acceuil</a>
</li>
<li>
<a href="./form.html" class="header-nav active" >créer un article</a>
</li>
</ul>
</header>
<div class="content">
<form>
<h2 class="title-underline">Ajouter un article ...</h2>
<div class="form-group">
<label>Auteur</label>
<input type="text" name="author">
</div>
<div class="form-group">
<label>Catégorie</label>
<input type="text" name="category">
</div>
<div class="form-group">
<label>Article</label>
<textarea name="content"></textarea>
</div>
<ul class="text-error" id="errors"></ul>
<div class="form-btn-container">
<button class="btn btn-secondary">Annuler</button>
<button class="btn btn-primary">Sauvegarder</button>
</div>
</form>
</div>
<footer>Blog</footer>
</div>
</body>
</html>
const form = document.querySelector("form");
const errorElement = document.querySelector("#errors");
let errors = [];
form.addEventListener("submit", async event => {
event.preventDefault();
const formData = new FormData(form);
const article = Object.fromEntries(formData.entries());
if (formIsValid(article)) {
try{
const json = JSON.stringify(article);
const response = await fetch("https://restapi.fr/api/olivier", {
method: "POST",
body: json,
headers: {
'Content-Type':'application/json'
}
});
const body = response.json();
console.log(body);
}catch(e){
console.error("error: ", e );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment