html form does not get sent after onSubmit function - html

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()">

Related

Node.JS - Express request returns undefined when when submitting a post request from a form

When I try to get an HTML form from using Node.JS/Express it seems to return a undefined value as the req.body returns an empty object.
Node
const express = require('express')
const bodyParser = require('body-parser')
const app = express()
const port = '3000'
app.use(bodyParser.urlencoded({ extended: true}))
app.use(bodyParser.json());
app.use(express.static('public'))
app.get('/',function(req, res) {
res.sendFile( __dirname + '/signup.html')
});
app.post('/', function(req, res) {
const FirstName = req.body.firstName
const LastName = req.body.lastName
console.log(FirstName)
console.log(LastName)
});
app.listen(port, function(err) {
if (err) console.log(err)
console.log('Local port started at', port)
});
HTML
<form action="/" method="post"\>
<label for="firstName"\>First Name\</label\>
<input class="form-grid__item--field" type="text" id="firstName" placeholder="First Name"\>
<label for="lastName">Last Name</label>
<input class="form-grid__item--field" type="text" id="lastName" placeholder="Last Name">
<label for="subscriberEmail">Email</label>
<input class="form-grid__item--field" type="text" id="subscriberEmail" placeholder="Email">
<input type="submit" class="form__button" value="Sign Me Up!">
</form>
Reformatted the code several times. Looked into the html form to ensure the action and methods where in place. When over body parser documentation to try and get more context but nothing.
The id field inside input label is used for referencing the element in the DOM.
In order to pass the input as a field in the request you must give it attribute name
<input class="form-grid__item--field" type="text" id="subscriberEmail" name="subscriberEmail" placeholder="Email">
The req.body searches for the name attribute in your form. Add the name attribute and then access them via req.body.theNameOfTheAttribute
<form action="/" method="post"\>
<label for="firstName"\>First Name\</label\>
<input class="form-grid__item--field" type="text" id="firstName" placeholder="First Name"\>
<label for="lastName">Last Name</label>
<input class="form-grid__item--field" type="text" id="lastName" placeholder="Last Name">
<label for="subscriberEmail">Email</label>
<input class="form-grid__item--field" type="text" id="subscriberEmail" placeholder="Email">
<input type="submit" class="form__button" value="Sign Me Up!">
</form>

Problem post data with Angular in MongoDB

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.

Sending a form on webhook + on a confirmation page

Here is the problem I have:
When validating my form I would like to :
1- Send the form information to a Webhook (to process the information) I would like it to be invisible for the user
2- Redirect the user to a confirmation page (or display a confirmation message on the form)
Here is my current form that only sends the info to the webhook:
<form method="post" action="https://hooks.zapier.com/hooks/catch/12195186/bzjhk97/">
<input id="prenom" type="text" name="first_name" placeholder="Votre prénom" required="required" />
<input id="email" type="email" name="email" placeholder="Votre adresse e-mail" required="required" />
<button id="submit" type="submit" class="btn">RECEVOIR LE KIT COMPLET</button>
I don't know if it's adjustable with Javascript or just HTML...
Thanks for your help :)
You can change your button type to "button" and then add a handler to that button to POST the data. In the example below I modified your code to do that and use fetch to POST the data to the endpoint.
Inside the ".then" part is the callback (this does not get execited until you receive the response from the fetch). This is where you would display the dialog to the user or redirect them to another page.
<form method="post" action="https://hooks.zapier.com/hooks/catch/12195186/bzjhk97/">
<input id="prenom" type="text" name="first_name" id="first_name" placeholder="Votre prénom" required="required" />
<input id="email" type="email" name="email" id="email" placeholder="Votre adresse e-mail" required="required" />
<button id="submit" type="button" class="btn" id="btn">RECEVOIR LE KIT COMPLET</button>
</form>
<script>
const getButton = document.getElementById('btn');
const getFirstName = document.getElementById('first_name');
const getEmail = document.getElementById('email');
fetch('https://hooks.zapier.com/hooks/catch/12195186/bzjhk97/', {
method: 'POST',
body: new URLSearchParams({
first_name: getFirstName.value,
email: email.value
})
})
.then(response => {
// Do stuff with the response
});

How can I submit just filled inputs of a form in ASP.NET Core?

I like to know if it possible to submit just filled inputs of a form and show their name and value in url in browser.
Example:
<form method="get">
<input name="firstname" value="a" />
<input name="lastname" value="" />
</form>
I like to show in url as:
?firstname=a
not as:
?firstname=a&lastname=
Thanks.
You'll have to use javascript to achieve this result. For example you can make empty inputs disabled so browser doesn't send their values
Form
<form method="get" id="the-form">
<input name="firstname" value="a" />
<input name="lastname" value="" />
<button type="submit">Submit</button>
</form>
Javascript
<script>
let form = document.querySelector('#the-form');
form.addEventListener('submit', () => {
let inputs = form.querySelectorAll('input');
for (let input of inputs) {
if (!input.value) {
input.disabled = true;
}
}
})
</script>

Do Not Load Page After Form Submit

I have created a basic HTML contact form using cgimail and everything works, but I can't get it to keep from redirecting somewhere after the form is submitted. I'm trying to instead use a bootstrap alert at the top of the page.
How do I get the form to submit, then keep it from redirecting?
here's the code:
<form method="post" action="/cgi-bin/cgiemail/forms/email.txt">
<fieldset>
<h2 id="contact-header">Contact</h2>
<label>Name:</label>
<input type="text" name="yourname" placeholder="" autofocus>
<label>Email Address:</label>
<input type="email" name="email" value="" placeholder="">
<label>Phone:</label>
<input type="tel" name="phone" value="" placeholder="">
<label>Message:</label>
<textarea name="message" rows="2"></textarea>
<br>
<button type="submit" id="formSubmit" class="btn">Send</button>
<input type="hidden" name="success" value="">
</fieldset>
</form>
Thanks,
Ryan
The "action" attribute in your form is telling it to send the browser over to that email.txt, which would then have control over whether or not to redirect you to another page. By default it would at least redirect you to the email.txt page for the post, but odds are cgi is doing extra stuff when posting to that page.
Using jQuery AJAX, you can do the following (this code skips error checking):
$('form').submit(function() {
var data = { };
data.yourname = $(this).find('input[name="yourname"]').val();
data.message = $(this).find('textarea[name="message"]').val();
// do the same as above for each form field.
$.post("/cgi-bin/cgiemail/forms/email.txt", data, function() {
//add the alert to the form.
$('body').prepend('div class="alert">Success!</div>');
});
return false;
});
You have two straight-forward choices. You can use jQuery and its forms plugin to turn this into an ajax operation or you can roll your own equivalent. It would look something like this (using jQuery):
$('form').submit(function() {
... get all values.
... ajax post the values to the server.
return false;
});
If you're using jQuery, then you could try cancelling the submit event. First give your form an id
HTML:
<form id="myform" ...
JavaScript:
$('#myform').on('submit', function(e) {
e.preventDefault();
$.ajax({
url: '/cgi-bin/cgiemail/forms/email.txt',
type: 'post',
data: $(this).serialize()
});
return false;
});