i am having an hard time understanding forms, i am submiting a form and saving the data in an array, but once the page is refreshed, the array does not have the data that the form submited. I tried also via a JSON file and inserting data via the POST method, but i am unable to save any type of data coming out of a form… Can someone help me resolve this issue ?
My code looks as follows:
const inputs = document.getElementsByClassName("inputs");
const form = document.querySelector("#form-user");
const [nameText, age, carBrand, textArea] = inputs;
const data = []
form.addEventListener("submit", (event) => {
event.preventDefault();
data.push({
name: nameText.value,
age: age.value,
carBrand: carBrand.value,
textArea: textArea.value
})
})
I also tried fetching the JSON file after submiting the form, but is also not working:
form.addEventListener("submit", (event) => {
event.preventDefault();
fetch("../data/data.json", {
method: "POST",
body: JSON.stringify({
name: nameText.value,
age: age.value,
carBrand: carBrand.value,
textArea: textArea.value
})
})
`
How do i save data coming out of a form ?
2
Answers
When you save the data in an array, it only persists as long as the page does not reload. Once the page reloads, the array reloads with it. All the variables go back to their initial states.
To persist/save the data, you can use localStorage or a backend database.
You can use
localStorage
to save data in client browser, here is the code after editing it:tell me if this works!