Answer the question
In order to leave comments, you need to log in
Why doesn't e.preventDefault work in this piece of code?
UPD: The solution was found, the problem was with the local server.
I'm learning how to use AJAX, the task is to write a simple POST request that, on clicking the "Submit" button, takes data from the form inputs and sends them to the db.json file.
I wrote the code, the data is sent and successfully saved in db.json, BUT I need the page not to be updated by clicking on the "Submit" button, therefore, I need to cancel its default actions. I'm trying to do it via e.preventDefault() but it doesn't work. Explain what is the reason? I don't understand anything.
HTML code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<form>
<input type="text" name="name">
<input type="text" name="age">
<button>Submit</button>
</form>
<script src="js/script.js"></script>
</body>
</html>
window.addEventListener("DOMContentLoaded", () => {
const form = document.querySelector("form");
function req(e) {
e.preventDefault();
let formData = new FormData(form);
formData.append("id", Math.random());
let obj = {};
formData.forEach((value, key) => {
obj[key] = value;
});
let json = JSON.stringify(obj);
const request = new XMLHttpRequest();
request.open("POST", "http://localhost:3000/people");
request.setRequestHeader("Content-type", "application/json; charset=utf-8");
request.send(json);
}
form.addEventListener("submit", (e) => req(e), {"once": true});
});
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question