posting data via a html form - javascript

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 ?

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:
const inputs = document.getElementsByClassName("inputs");
const form = document.querySelector("#form-user");
const [nameText, age, carBrand, textArea] = inputs;
const data = JSON.parse(localStorage.getItem('form-data')) || [];
form.addEventListener("submit", (event) => {
event.preventDefault();
const formData = {
name: nameText.value,
age: age.value,
carBrand: carBrand.value,
textArea: textArea.value
};
data.push(formData);
localStorage.setItem('form-data', JSON.stringify(data));
});
tell me if this works!

Related

Strange behavior after React state update with new entry

In my CRUD application, I am facing a problem every time the initial state ( array list ) updates with a new entry.
Clicking on an add button should open a modal and fill out a react-hook-form. On submit should update the state by adding the new entry.
Clicking on the edit button should open a modal and load data to the react-hook-form. On submit should update the state by updating the corresponding entry.
Everything works fine until I add a new entry in the state.
The entry is displayed in the table and clicking the edit button of that or any other entry works fine. When clicking the button of any entry, again the isEdit state stops to change as it should. I have a working demo here
In App.js
These are the states in the application. One for users list, one for distinguishing between add and update functions, and the last for passing the default values to the form when updating a user.
const [users, setUsers] = useState([]);
const [isEdit, setIsEdit] = useState(false);
const [defaultValues, setDefaultValues] = useState(initialDefaultValues);
There is a list of users coming from a GET request. When the request resolves successfully, I set the returned data to the state.
// get Users
const fetchUsers = async () => {
const res = await fetch("https://jsonplaceholder.typicode.com/users");
const resData = await res.json();
if (res.status === 200) {
setUsers(resData);
} else {
alert(resData);
}
};
// execute on component render
useEffect(() => {
fetchUsers();
}, []);
There is a component that renders a react-bootstrap-table-next and takes the data from the state.
<UsersTable
data={users}
prepareUpdateUser={prepareUpdateUser}
prepareDeleteUser={prepareDeleteUser}
/>
This table has two buttons for each entry. An edit button and a delete button. On click these buttons the two prepare functions are executed accordingly (prepareUpdateUser, prepareDeleteUser). This is the code for the prepareUpdateUser(). The function takes the user as an argument, changes the isEdit state to true, updates the defaultValues to pass to the react-hook-form, and finally opens the modal.
const prepareUpdateUser = (user) => {
setIsEdit(true);
setDefaultValues({
id: user.id,
name: user.name,
email: user.email
});
toggleUserModal();
};
When the modal close, I reset the isEdit and `defaultValues`` state to their initial values.
const [userModal, toggleUserModal] = useModali({
animated: true,
title: isEdit ? "Update User " : "Add User ",
onHide: () => {
isEdit && setIsEdit(false);
setDefaultValues(initialDefaultValues);
}
});
The problem is that after adding a new entry in the state and then try to click the edit button of any entry, everything works, but the next time you click the button the isEdit state stops updating every time the modal closes, and each time the prepareUpdateUser runs. The problem does not appear when updating an entry.
This is the code to add a new user to the users list
const addUser = (data) => {
const newArray = users.slice();
newArray.splice(0, 0, data);
setUsers(newArray);
toggleUserModal();
};
This is the code to update a user
const updateUser = (data) => {
const updatedUser = users.findIndex((user) => user.email === data.email);
const newArray = users.slice();
newArray[updatedUser] = data;
setUsers(newArray);
toggleUserModal();
};
If you are going to use the demo link, here are the steps to reproduce the problem.
Click on any edit button. Everything loads and the isEdit state is true.
Click the add button. The form is empty and the isEdit state is false.
Add a new entry.
The list updates with the new entry.
Click an edit button. Seems to work.
Click again an edit button and now isEdit is false and no data loaded in the form
Has anyone faced something similar? I am fairly new to react, and I cannot understand why this happens. Any advice will be really helpful.
Thank you all in advance.
**I have just modified below block of code**
const prepareUpdateUser = (user) => {
setIsEdit(true);
setDefaultValues({
id: user.id,
name: user.name,
email: user.email
});
};
**Newly added one useEffect**
useEffect(() => {
if (isEdit) {
toggleUserModal();
}
}, [isEdit]);
try this. Please give your valuable feedback

How execute javascript after a component change in angular?

My code works fine when I write in browser localhost:4200/pay;id=1. This show Pay component with credit card fields generated by a external javascript (This javascript script is loaded from this component). But if i come from another component to this, Pay component doesn't show the credit card fields but load external script. How can I fix this?
My code
first.component.ts
let datos = {
id:'6'
}
this.router.navigate(['pay',datos]);
pay.component.ts
ngOnInit(): void {
this.loadScripts();
}
loadScripts() {
this.dynamicScriptLoader.load('2payjs').then(data => {
// Script Loaded Successfully
console.log('All elements loaded successfully')
this.loadElement();
}).catch(error => console.log(error));
}
loadElement(){
let that = this;
let id = this.router.snapshot.paramMap.get('id');
window.addEventListener('load', function() {
// Initialize the JS Payments SDK client.
let jsPaymentClient = new TwoPayClient('AVLRNG');
// Create the component that will hold the card fields.
let component = jsPaymentClient.components.create('card');
component.mount('#card-element');
// Handle form submission.
document.getElementById('payment-form').addEventListener('submit', (event) => {
event.preventDefault();
/// Extract the Name field value
const billingDetails = {
name: document.querySelector('#name').value
};
// Call the generate method using the component as the first parameter
// and the billing details as the second one
jsPaymentClient.tokens.generate(component, billingDetails).then((response) => {
//console.log(response.token);
let data = {
token:response.token
}
}).catch((error) => {
console.error(error);
});
});
});
}
const navigationExtras: NavigationExtras = {
queryParams: {
id: 1,
},
queryParamsHandling: 'merge'
};
this.router.navigate(['pay'], navigationExtras);
you need navigationExtras in order to create params in your router link and able to fetch by another component
Already solved. I just delete window load event listener.

Load graphical data even without passing the parameters through the filter (vue.js)

I have a problem, as soon as my page is opened, the graphics come blank, because I passed the callback for the graphics data to be generated through params request
I would like, as soon as the page is opened, to make a GET of the general data, and when requested by the filter then yes load with params
Unfortunately, I do not know which logic to use
mounted() {
this.refresh()
},
methods: {
refresh () {
this.$axios.get()
var situacao = this.situacao.map(st => st.id)
var cliente = this.cliente.id
var especialidade = this.especialidade.id
var tipo = this.tipos.id
var helpDesk = this.helpDesk.id
var supervisor = this.supervisor.id
var params = {
tipo: tipo,
situacao: situacao,
cliente: cliente,
helpDesk: helpDesk,
especialidade: especialidade,
supervisor: supervisor
}
this.$axios.get("/Operacional/GetRelatorio/?" + qs.stringify( params, { arrayFormat: 'repeat' }))
.then(res => {
this.prazos = res.data
this.$refs.chart1.updateSeries([{
name: 'NO PRAZO',
data: [this.prazos.noPrazo, this.prazos.emDia, this.prazos.atrasadas]
}])
})
I would like to request the params only when selecting the filter, and when not, it makes a normal GET, without params, so that the graphics once the page is loaded do not remain blank
You can make use of data() property in the component and define a variable with default value false.
data () {
return {
filterApplied: false;
}
}
Then when selecting the filter, change the data property to true and on the basis of this value send the request with or without params.

React useState Hook - Can't Clear State on Form Data

Slightly novice react hooks user here. Trying to submit a blog post form, consisting of a title, author and URL. I can submit my form correctly and values are saving in database, but I can't clear the data from the form.
I'm holding state like this
const [newBlog, setNewBlog] = useState({ url: "", author: "", title: "" });
and handling form change to update state like this:
const handleBlogChange = e => {
const { name, value } = e.target;
setNewBlog({ ...newBlog, [name]: value });
};
example setup of one my input fields (identical across all three)
<form className="form" onSubmit={addBlog}>
<div className="col-lg-9">
<input
className="form-control"
id="title"
aria-describedby="emailHelp"
placeholder="Enter title"
name="title"
value={newBlog.title}
onChange={handleBlogChange}
/>
</div>
and this is my addBlog function. you can see where I commented out one version of clearing the state which is causing problems.
const addBlog = event => {
event.preventDefault();
const { url, title, author } = newBlog;
const blogObject = {
url,
title,
author
};
blogService
.create(blogObject)
.then(data => {
setBlogs(blogs.concat(data));
showMessage(`Success! ${newBlog.title} by ${newBlog.author} was added`);
// setNewBlog([...newBlog, { url: "", title: "", author: "" }]);
})
.catch(error => {
showMessage(
`Sorry can't add blog. Here's why: ${error.response.data.error}`,
false
);
});
};
I've also tried different variations which are leaving the data in the form, no errors, but not clearing out the form. Examples of this include
setNewBlog(''), setNewBlog([]) and
setNewBlog(newBlog.title='')
Nothing is working.

How to reset json file in nodejs

I need to reset a json file to an original state after a button is clicked. Currently, I am modeling with router, and I need help to extend my existing code.
This is a code snippet I wrote on server.js file, the one that I run "nodemon" to start the server.
var messages = [{index:0, rating:0}, {index:1, rating:0}]
app.get('/votes', (req, res) =>{
res.send( messages )
})
app.post('/votes', (req, res) =>{
votes.push(votes)
res.sendStatus(200)
})
so my initial state on file 'votes' (json format) is:
[{"index":0,"rating":0}, {"index":1, "rating":0}]
After some user actions, I'll add some data to this json file using this code:
<body>
// some logic here
<script>
$(() => {
$("#submit").click(()=>{
var message = [ { index:1, rating: $("#input").val()},
{ index:2, rating: $("#input2").val()}]
postMessage(message)
})
})
function postMessage(message) {
$.post('http://localhost:8080/votes', message)
}
</script>
</body>
and then I have the following in my json file
[{"index":0,"rating":0}, {"index":1, "rating":0}, {"index":1, "rating":1}, {"index":2, "rating":3}]
QUESTION: How do I reset the json file (not json variable) into the initial state with a button click for a new transaction?
I am just doing prototyping, so a quick and dirty way may work.
I'd recommand build or use some sort of user verification, and for each user have a copy of the initial data just for him. Keep in mind that this data will never garbage collected so you will have to manage deletion by yourself. I used basic IP that is given by express but that is not a good practice.
Use npm-memorystore which will give your some memory management.
If you want to identify users you can use express-session, express-jwt
var messages = [{
index: 0,
rating: 0
}, {
index: 1,
rating: 0
}];
var usersMessages = {};
app.get('/votes', (req, res) => {
var userIp = req.ip;
usersMessages[userIp] = [].concat(messages);
res.send(usersMessages[userIp]);
});
app.post('/votes', (req, res) => {
var userIp = req.ip;
var userVotes = usersMessages[userIp];
if (!userVotes)
usersMessages[userIp] = [].concat(messages);
usersMessages[userIp].push(req.body.votes);
res.sendStatus(200)
});
Take a look this:
$(() => {
let message = [];
$("#submit").click(() => {
//fill with values
message = [
{ index: 1, rating: $("#input").val() },
{ index: 2, rating: $("#input2").val() }
];
postMessage(message); //send post
message = []; //reset array
});
function postMessage(message) {
$.post("http://localhost:8080/votes", message);
}
});
Hope this helps. =D
What you need to do is, just remove all of the object from array.
You can do that as follow.
var messages = [{"index":0,"rating":0}, {"index":1, "rating":0}, {"index":1, "rating":1}, {"index":2, "rating":3}];
messages.length = 1;
console.log(messages);
Another way.
var messages = [{"index":0,"rating":0}, {"index":1, "rating":0}, {"index":1, "rating":1}, {"index":2, "rating":3}];
messages = messages.slice(0,1);
console.log(messages);
What above code do is, it will just set array back to it first value.

Categories

Resources