Skip to content

Instantly share code, notes, and snippets.

@DerexScript
Created September 16, 2022 22:49
Show Gist options
  • Save DerexScript/e4224a254a7829340bc8ffa1c9832f4f to your computer and use it in GitHub Desktop.
Save DerexScript/e4224a254a7829340bc8ffa1c9832f4f to your computer and use it in GitHub Desktop.
post using Content-Type application/x-www-form-urlencoded with fetch
<!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">
<title>Home</title>
</head>
<body>
<form action="./main.php" id="idForm">
<div>
name: <input type="text" name="name" value="name"><br>
surname: <input type="text" name="surname" value="surname"><br>
username: <input type="text" name="username" value="username"><br>
email: <input type="text" name="email" value="email"><br>
password: <input type="text" name="password" value="password"><br>
<button type="submit">Enviar</button>
</div>
</form>
<script>
let myForm = document.getElementById("idForm");
myForm.addEventListener("submit", async evt => {
evt.preventDefault();
const data = await fetch(myForm.action, {
method: "POST",
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams(new FormData(myForm))
});
console.log(await data.text());
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment