Problem post data with Angular in MongoDB - html

i'm trying to do a crud in Angular 14.
All works fine, but when i put in my form an input to update my data, this crashed.
That input are the first of my form.
This is my component.html
<form>
<input type="hidden" name="_id" [(ngModel)]="orderService.selectedOrder._id">
<input id="client" type="text" class="form-control" name="client" placeholder="Client name" [(ngModel)]="orderService.selectedOrder.client"/>
<input id="client" type="text" class="form-control" name="price" placeholder="Price" [(ngModel)]="orderService.selectedOrder.price"/>
</form>
This is my component.ts
addOrder(form: NgForm){
if(form.value._id){
this.orderService.updateOrder(form.value).subscribe(
(res) => {
//console.log(res);
form.reset();
this.getOrders();
},
err => console.log(err)
);
}else{
// Here i want to skip form.value._id in createOrder()
this.orderService.createOrder(form.value).subscribe(
res => {
form.reset();
this.getOrders();
},
err => console.log(err)
)
}
}
And finally my orderService
createOrder(order: Order){
return this.http.post(this.URL_API, order);
}
updateOrder(order: Order){
return this.http.put(`${this.URL_API}/${order._id}`, order);
}
When i remove the hidden input, the problem of create new data are solved, but i cant update data.
I think the problem is when I create a new order, it takes the value of the _id input value from the createOrder method. I don't know how to remove this value when making the post from my method.

Related

How to prevent a slow post form UX breaking required attribute?

I have a form that looks like:
<form method="POST">
<label>Your name:
<input name="name" required>
</label>
<input type="submit" onclick="this.form.submit(); this.disabled=true; this.value='Sending…';">
</form>
The form's backend takes upto 10 seconds to respond (blockchain!), hence the disabled input to prevent multiple retries. However it then breaks the required validation and users can send in empty payloads.
Any tips how to prevent this using Vanilla or maybe VueJS?
Many thanks,
Using Vuejs you can try :
#submit.prevent="action" in form tag instead of onClick....
add async await with try catch
if you want you can also disable your button in submit to be sure users can't send an empty payloads
here's a gist code : https://gist.github.com/jiyuuki/e6f8f7bb67b48014223d1561119ac2fa
Try to control the button with a data property like below.
export default {
name: 'Form',
data() {
return {
isLoading: false,
}
},
methods: {
async submitForm() {
this.isLoading = true;
await this.form.submit(); // Assuming this is where you make the time taking call
this.disabled=true;
this.value='Sending…';
}
}
}
<form method="POST">
<label>Your name:
<input name="name" required>
</label>
<input
:disabled="isLoading"
type="button"
#click="submitFrom">
</form>
Reset the isLoading to false after the response reaches.

html form does not get sent after onSubmit function

The geocodeAddress() function uses fetch to send a http request. Before I added "event.preventDefault()" as a parameter to the function, it would not run properly (TypeError: Network Error) as the request was being interrupted by the page reloading caused by the form being sent. However, once I added it, the form no longer gets sent. I don't think the problem lies with the php code as I have not altered it at all. What could be causing this?
I had the same error in this post before
'TypeError: NetworkError when attempting to fetch resource' on form submit ReactJS
<form action="private/database.php" method="POST" onsubmit="geocodeAddress(event.preventDefault())">
<input type="text" name="surname" placeholder="性氏" required><br>
<input type="text" name="given_name" placeholder="名字" required><br>
<label for="male">
<input type="radio" id="male" name="gender" required>
男性
</label>
<label for="female">
<input type="radio" id="female" name="gender">
女性
</label><br>
<input type="text" name="email" placeholder="電子信箱" required><br>
<input type="text" name="phone_number" placeholder="電話" required><br>
<input type="text" id="address" name="address" placeholder="地址" required><br>
<input type="hidden" id="lat" name="lat">
<input type="hidden" id="lng" name="lng">
<input type="date" name="cleaning_date" required><br>
<input type="submit" name="form_submit">
</form>
<script>
function handleErrors(res) {
if (!res.ok) {
throw Error(res.statusText);
}
return res;
}
function geocodeAddress() {
const address = document.getElementById('address').value;
fetch(`https://maps.googleapis.com/maps/api/geocode/json?address=${address}&key=AIzaSyDxsdfWYv25UrruPXLqeXKVYUnD-VyReA`)
.then(handleErrors)
.then(res => res.json())
.then(data => {
console.log(data);
document.getElementById('lat').value = data.results[0].geometry.location.lat.toString();
document.getElementById('lng').value = data.results[0].geometry.location.lng.toString();
})
.catch(error => console.log(error));
}
</script>
This is a pretty simple issue. event.preventDefault() stops the default action, that the event would do, which in this case is submitting the form. This means the fetch isn't interrupted, but of course, the form doesn't submit.
In order to fix this, you have to manually submit the form after the fetch has succeeded. This can be easily done by executing event.target.submit(). (event.target references the form, so we are simply calling the submit function of the form) Here is the modified geocodeAddress function, that should do just that:
function geocodeAddress(event) {
event.preventDefault() // prevent the submit from happening immediately
const address = document.getElementById('address').value;
fetch(`https://maps.googleapis.com/maps/api/geocode/json?address=${address}&key=AIzaSyDxsdfWYv25UrruPXLqeXKVYUnD-VyReA`)
.then(handleErrors)
.then(res => res.json())
.then(data => {
console.log(data);
document.getElementById('lat').value = data.results[0].geometry.location.lat.toString();
document.getElementById('lng').value = data.results[0].geometry.location.lng.toString();
event.target.submit() // trigger the submit again once the fetch has finished
})
.catch(error => console.log(error));
}
Oh and also, in the onsubmit of the form, you should just have the "geocodeAddress()".
<form action="private/database.php" method="POST" onsubmit="geocodeAddress()">

Posting to database from html form

I'm sure this is a simple thing I am missing but the internet seems devoid of the documentation to do this simple thing.
I am trying to grab data from my HTML and send it to my database. I forgot to add my script tag to the HTML for a while but it was working and sent two tests into the database before it stopped working and said my validations failed (both title and blog are required).
What am I missing? Thank you for your help!
my form:
<form
action="/api/blog"
method="POST"
id="blog-form"
class="blog-form container mt-5"
enctype="multipart/form-data">
<label for="title">Title</label>
<input type="text" name="title" />
<br />
<label for="blog">Text</label>
<textarea name="blog" rows="15" cols="120"></textarea>
<input type="submit" value="submit" />
</form>
JS:
const form = document.getElementById("blog-form");
form.onsubmit = (e) => {
e.preventDefault();
console.log(e.target.value); // this is coming back undefined
};
API route:
router.post("/blog", async (req, res) => {
console.log(req.body);
const blog = new Blog({
title: req.body.title,
blog: req.body.blog,
});
try {
await blog.save();
res.status(201).json(req.body);
} catch (err) {
console.error(err.message);
res.status(500).send("server error");
}
got it working by removing the "enctype="multipart/form-data" from the HTML and removing all of the JS

Why is OnChange not working when used in Formik?

I am trying to use Formik in React for a dummy app. I am not being able to type anything in either of the input boxes if I give value as a prop. On the other hand, if I skip the value props, then I can type in the boxes but the same is not reflected as the value while submitting.
Here's the code:
export default class DashboardPage extends React.Component {
render() {
return (
<Formik
initialValues={{ fname: "", lname: "" }}
onSubmit={(values) => {
alert(values.fname);
}}
render={({ values, handleChange, handleSubmit }) => (
<form onSubmit={handleSubmit}>
<input type="text" placeholder="First Name" name="fname" onChange={handleChange} value={values.fname} />
<input type="text" placeholder="Last Name" name="lname" onChange={handleChange} value={values.lname} />
<button type="submit>ADD<button/>
</form>
)}
/>
);
}
}
I may be very wrong here and might be over-looking a minor error, but any help/suggestion is appreciated!
export default class DashboardPage extends React.Component {
render() {
return (
<Formik
initialValues={{ fname: "", lname: "" }}
onSubmit={ (values) => alert(values.fname) }
>
{ props => (
<React.Fragment>
<form onSubmit={handleSubmit}>
<input type="text" placeholder="First Name" name="fname" onChangeText={props.handleChange('fname')} />
<input type="text" placeholder="Last Name" name="lname" onChangeText={props.handleChange('lname')} />
<button type="submit>ADD<button/>
</form>
</React.Fragment>
)}
</Formik>
)
}
}
Hi mate can you please try this?
Another possibility for this weird behavior is putting your component inside a function and sending the props as function parameters instead of using a functional component with props as parameters.
When a component is inside a function you lose react component lifecycle and the parameters will not refresh even when its values change.
Make sure your form elements are properly configured as react elements.
Mine was also not working, I gave id prop in my TextField and now it works
const formik = useFormik({
initialValues: {
username: "",
password: "",
},
onSubmit: (values) => {
console.log(values);
// onLogin(values.username, values.password);
},
});
<form onSubmit={formik.handleSubmit}>
<TextField
value={formik.values.username}
onChange={formik.handleChange}
id="username"
name="username"
variant="outlined"
style={TextField1style}
placeholder="Enter username"
fullWidth
required
//.
// .
// .
// other code
enter image description here

post form data and show in server

I have a simple form, I just want to see which fields are sent to server. But in the server side, I only get the <input type="text"> field value. Why the server can't get the <select> and <input type="file" /> value?
HTML:
<form action="http://localhost:8100/" method="POST">
<div>
<select>
<option value="op1" selected="selected">Option1</option>
<option value="op2">Option2</option>
</select>
</div>
<div>
<input type="file" value="select a file"/>
</div>
<div>
<label>Your Hero: </label><input type="text" name="hero" />
</div>
<input type="submit" value="submit" />
</form>
Server:
var http = require("http");
http.createServer(function(req, res) {
if (req.method == 'POST') {
var body = '';
req.on('data', function (data) {
body += data;
console.log(body);
});
req.on('end', function () {
console.log("request data complete");
});
res.end("post request");
} else {
res.end("get request");
}
}).listen(8100);
Your select and file input elements are missing name attribute. All form elements you wish to be submitted must have a unique name attribute. name attribute will the identifier for the value of element when the data has been submitted through POST and GET.
You can read about it in the specs in here: http://www.w3.org/TR/html5/forms.html#naming-form-controls:-the-name-attribute
I think you just forgot the "name" attributes in this form elments. Add it and it should work. Cheers