Hello and thanks for reading. I try to use express-validator. It works fine and block the post if for instance the name input is empty. But I don't know how I can get the error message on the front side. I have tried lot of things without success. Hope somebody can help and sorry for the size of the message. Here is a link to the doc of express validator if it can help ( https://express-validator.github.io/docs/ )
My code...
I have create a basic form:
<form id="sign-in">
<div class="form-group">
<label for="nom">name</label>
<input id="name" type="text" class="form-control" placeholder="name" autocomplete="family-name">
</div>
<div class="form-group">
<label for="username">username</label>
<input id="username" type="text" class="form-control" placeholder="username" autocomplete="given-name">
</div>
<div class="form-group">
<label for="email">email</label>
<input id="email" class="form-control" type="email" placeholder="monemail#gmail.com" autocomplete="email"></input>
</div>
<div class="form-group">
<label for="password">password</label>
<input id="password" class="form-control" type="password" autocomplete="current-password"></input>
</div>
<div class="form-group">
<label for="confirm-password">confirm-password</label>
<input id="confirm-password" class="form-control" type="password" autocomplete="current-password"></input>
</div>
<button type="submit" class="btn btn-primary">sign-in</button>
</form>
</section>
<footer>
</footer>
<script type="module" src="/js/sign-in.js"></script>
Then I do my fetch on the file sign-in.js:
document.getElementById('sign-in').addEventListener('submit', event => {
event.preventDefault()
const name = document.getElementById('name').value
const username = document.getElementById('username').value
...
// Use fetch to post data into the DB
window.fetch(`${config.serverHost}/sign-in`, {
method: 'post',
body: JSON.stringify({
name,
username,
...
})
}).then((res, errors) => {
if (res.status === 200) {
window.parent.location.reload()
} else if (res.status === 422) {
DONT KNOW WHAT TO DO TO GET MY ERROR MESSAGE
}
})
})
And finaly the server side:
app.post('/sign-in', (req, res, next) => {
// Start express validator //
req.checkBody('name', 'Please write your name').notEmpty()
req.checkBody('username', 'Please write your name').notEmpty()
...
const errors = req.validationErrors()
if (errors) {
SEND ME BACK MY ERROR MESSAGE
} else {
this part works fine, thank you
}
})
You have two options here depending on how your client is setup:
Use either express-flash or connect-flash to send errors back to your view. See this for the differences.
Use res.json to send back the errors object you created from validationErrors(). Be sure to set the appropriate HTTP status as well.
As I found the solution I post it, it may be useful for others.
Here is the sign-in.js file:
.then(res => {
if (res.status !== 200) {
res.json()
.then(res => errorsMessages.innerHTML = res.map(e => `<p>${e.msg}</p>`).join(''))
} else {
window.parent.location.reload()
}
})
And the code for the server:
const errors = req.validationErrors()
if (errors) {
res.status(422).json(errors)
} else {...}
Thank you Francisco for your help.
Related
I searched for a long time without results about this question. The problem is that when I try to send an asynchronous request to another web page I don't have any response. I think the problem is where the FormData takes its values but I don't know why... Here is the code:
const addBooking_form = document.getElementById("form_addResa");
addBooking_form.addEventListener("submit", (event) => {
event.preventDefault();
// Send asynchronous request to /api/booking/new
const formData = new FormData(addBooking_form);
const searchParams = new URLSearchParams(formData);
console.log(formData);
console.log(searchParams);
const asyncReqAdd = fetch("api/booking/new", {
method: "POST",
body: formData
});
asyncReqAdd.then(response => {
return console.log(response.text() == 'undefined' ? 'Fetch reponse <=> undefined' : response);
}).then((response) => {
console.log(response)
table.innerHTML = response;
});
return console.log('New booking submited');
})
I know that the link and the form id are correct...
HTML FORM :
<form id="form_addResa">
<div class="fieldset flexCol-around">
<label for="input_lieu">Lieu *</label>
<select id="input_lieu" name="place">
<option value="none">< Séléctionner un lieu ></option>
<option value="Salammbô">Salammbô</option>
<option value="Pergola">Pergola</option>
<option value="Salon Jaune">Salon Jaune</option>
<option value="1001 Bougies">1001 bougies</option>
</select>
<div class="flexRow-around">
<div class="flexCol-around">
<label for="input_date">Date *</label>
<input id="input_date" type="date" name="date">
</div>
<div class="flexCol-around">
<label for="input_time">Heure *</label>
<input id="input_time" type="time" name="time">
</div>
</div>
<label for="input_nom">Nom *</label>
<input id="input_nom" type="text" name="name">
<label for="input_prenom">Prénom *</label>
<input id="input_prenom" type="text" name="firstName">
</div>
<div class="fieldset flexCol-around">
<label for="input_couverts">Nombre de couverts *</label>
<input id="input_couverts" type="number" name="coverts">
<label for="input_intExt">Client interne / externe *</label>
<select name="intExt" id="input_intExt">
<option value="ext">Externe</option>
<option value="int">Interne</option>
</select>
<label for="input_contacte">Contacter le client *</label>
<input id="input_contacte" type="text" placeholder="Numéro de chambre / téléphone / E-mail" name="contact">
</div>
<div class="fieldset">
<textarea id="input_note" placeholder="Note :" name="notes"></textarea>
</div>
<div class="flexRow-around">
<input type="reset" value="Annuler" style="background: white;">
<input type="submit" onclick="unselectBooking();">
</div>
</form>
Can you give me a solution for this?
You could use async/await with a try catch block to see what goes wrong.
Something like this (pseudo):
addBooking_form.addEventListener("submit", async (event) => {
event.preventDefault();
const { date, time, name, place } = Object.fromEntries(new FormData(event.target))
try {
const respone = await fetch("api/booking/new", {
method: "POST",
body: { date, time, name, place }
});
const data = await response.json()
// do something with data
console.log(data)
} catch(e) {
// do some error handling
console.log('error', e)
}
})
Update: you can use Object.formEntries on FormData to get the values of your named input fields and then pass them to the body. This way, you should have valid JSON data.
I also removed the element selector since you already got the element via event
I hope you are doing great, I am using Emailjs in React to get Emails. I configure Emailjs and it is properly sending test Emails but when I am trying to send from my project so it's not sending and even it is also not showing any error
Here is the template of the Email
Here is the ID and token which I hide but I am just showing this image to explain
clearly
(1) Here i import emailjs
import emailjs from '#emailjs/browser';
(2) Here is the function that will send the email, (Here in the fourth parameter I am just showing 5 characters as I hide in the above image )
function sendEmail(e) {
e.preventDefault();
emailjs.send('gmail', 'zaryabkhan864', e.target, 'G5CpT9*******')
.then((result) => {
console.log(result.text);
}, (error) => {
console.log(error.text);
});
e.target.reset()
}
(3) Here is the Form code
<form onSubmit={sendEmail}>
<div className="mb-3">
<label htmlFor="name" className="form-label">Your Name</label>
<input type="text" className="form-control" id="name" placeholder="Muhammad Zaryab Khan" name="name" />
</div>
<div className="mb-3">
<label htmlFor="email" className="form-label">Email address</label>
<input type="email" className="form-control" id="exampleFormControlInput1" placeholder="name#example.com" name="email" />
</div>
<div className="mb-3">
<label htmlFor="exampleFormControlTextarea1" className="form-label">Your Message</label>
<textarea className="form-control" id="Message" rows="5" name="message"></textarea>
</div>
<button type="submit" className="btn-theme">Send Message <i className="fa fa-paper-plane ms-2"></i></button>
</form>
Now I am receiving this error
add ref atribute for form, and ad useRef
const form = useRef<HTMLFormElement>(null);
after you should change e.target => form.current
const form = useRef();
const sendEmail = (e) => {
e.preventDefault();
emailjs.sendForm('service_id', 'template_id', form.current, 'user_id')
.then((result) => {
console.log(result.text);
}, (error) => {
console.log(error.text);
});
alert("Email Send");
};
Hi I'm using Angular 2+ to integrate the sandbox PayPal checkout button with my form and throughout most of the process it works fine. The issue I'm having is that the onApprove() method seems to get called twice after the process ends which I can see because the HTTP request I have in that method gets called twice.
I've tried looking online for anyone who has experienced a similar problem but I can't find any resources on how to fix it. I have a few warnings in Chrome's console but these seem to be unrelated to the problem.
The console.log statements in createSubscription and onCancel only print once so I think that eliminates the possibility of there being some kind of duplicate window.
My code seems to be fairly similar to everyone else's implementation which I've seen on the web which is why I can't wrap my head around why it doesn't work.
component.ts
ngAfterViewInit() {
paypal.Buttons({
onInit: (data, actions) => {
},
onClick: (actions) => {
},
createSubscription: (data, actions) => {
return actions.subscription.create({
'plan_id': this.planID,
});
},
onApprove: (data, actions) => {
console.log(data + ' transaction approved');
this.submitLoginDetails();
//this.getSubcriptionDetails(data.subscriptionID);
// use auth login method and redirect to /home
},
onCancel: (data) => {
console.log('Transaction cancelled');
},
onError: (err) => {
console.log(err);
}
}).render(this.paypalElement.nativeElement);
}
component.html
<!-- LOGIN FORM -->
<div id='payment' [hidden]="stepCounter!==2">
<form #loginForm='ngForm'>
<div id="user-data">
<div class="form-group">
<label for="name" required>Name</label>
<input type="text" name="name" id="name" class="form-control" ngModel minlength=1 #name='ngModel'>
<span class="help-block" *ngIf='(!name.valid || name.value.length === 0) && name.touched'>Please enter a valid name</span>
</div>
<div class="form-group">
<label for="email" required email>Email</label>
<input type="email" name="email" id="email" class="form-control" ngModel email #email='ngModel'>
<span class="help-block" *ngIf='(!email.valid || email.value.length === 0) && email.touched'>Please enter a valid email</span>
</div>
</div>
<div class="form-group">
<label for="pwd">Password</label>
<input type="password" name="password" id="password" class="form-control" ngModel required minlength=6 #password='ngModel'>
<span class="help-block" *ngIf='(!password.valid || password.value.length === 0) && password.touched'>Please enter at least six characters</span>
</div>
<div #paypal></div>
<span class="help-block" *ngIf='buttonError && !loginForm.valid'>Please make sure the values above are valid before checking out</span>
</form>
</div>
Console after the checkout has been completed and onApprove() has been called
I have a contact form which I am trying to POST the data via AXIOS using formData to send email via WP_mail.
Submitting the form seems to be working in the sense of:
The page isn't refreshing/adding parameters to the url
Using for (var value of formData.values()) {console.log(value);} to check what values are being grabbed by formData, console.log shows the different input values
response.status is showing 200
The problems start with response.data returning 0 rather than the data from the form that is being submitted.
This is my form
<form class="js-process dark-form">
<fieldset>
<label for="name">First name*</label>
<input type="text" name="name" placeholder="Enter your first name" />
<label for="last-name">Last name*</label>
<input type="text" name="last-name" placeholder="Enter your last name" />
<label for="email-address">Email address*</label>
<input type="email" name="email-address" placeholder="Enter your email address" />
<label for="telephone">Telephone*</label>
<input type="tel" name="telephone" placeholder="Enter your phone number" />
</fieldset>
<fieldset>
<label for="enquiry-form">Nature of enquiry*</label>
<!-- TEMP -->
<select id="enquiry-form" name="enquiry-form" data-label-value="test">
<option disabled value="">test</option>
<option value="test">test</option>
<option value="test">test</option>
<option value="test">test</option>
</select>
<label for="your-message">Your message*</label>
<textarea name="your-message" placeholder="Please tell us your message"></textarea>
</fieldset>
<input type="submit" value="Submit">
</form>
This is my JS to POST the form data
import axios from 'axios';
const processForm = (e) => {
const form = e.target;
e.preventDefault();
// let formData = new FormData(form);
const formData = new FormData();
// Console.log all formData values for testing
for (var value of formData.values()) { console.log(value); }
formData.append('action', 'contact_form');
formData.append('first_name', 'my first name');
axios({
method: 'POST',
url: WP.ajax,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
data: formData,
})
.then(function (response) {
console.log(response);
console.log(response.data);
console.log(response.status);
console.log(response.statusText);
console.log(response.headers);
console.log(response.config);
},
(error) => {
console.log(error);
});
return false;
};
const initProcessForm = () => {
const forms = document.querySelectorAll('.js-process');
forms.forEach(form => {
form.addEventListener('submit', processForm);
});
};
export default initProcessForm;
I'm not sure what I am missing here to get the data from the form to POST correctly. I know i've not even got round to the WP_mail side of things! I am new to using AXIOS so if anyone can point me in the right direction with this code or has a better way of doing this i'd be grateful to know : )
Thanks in advance.
I wrote a toy program to learn AJAX, which is to submit the user registration form to web server, however, the program on the server side cannot receive the data. I guess the error is on the following JS code using jQuery:
$(document).ready(function() {
$('#registerForm').submit(function() {
var formData = $('#registerForm').serialize();
$.post('/admin/user/signup', formData, registerResults);
},
registerResults: function() {
console.log("register success!");
} // end of registerResults
}); // end of ready
The corresponding html form is as following:
<form class="form-horizontal" role="form" id='registerForm' method='POST' action="/admin/user/signup">
<div class="form-group">
<label class="col-sm-3 control-label" for="fullname">Fullname: </label>
<div class="col-sm-5">
<input class="form-control" type='text' id="fullname" name='fullname' placeholder="Full Name" />
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label" for="username">Username: </label>
<div class="col-sm-5">
<input class="form-control" type='text' id="username" name='username' placeholder="Username" />
</div>
</div>
<div class="form-group">
<input type='submit' value="Submit" class="register-form-button" form='user-create-form' />
</div>
</form>
can someone help me with my JS code using jQuery? Thanks a lot!
Like Felix said, your JavaScript syntax is invalid. Open up the JS console and refresh the page, and you'll see syntax errors.
Here's a shot at fixing it:
$(document).ready(function () {
$('#registerForm').submit(function() {
var formData = $('#registerForm').serialize();
$.post('/admin/user/signup', formData)
.done(registerResults)
.fail(registerError);
});
function registerResults() {
console.log("register success!");
}
function registerError() {
console.log("There was an error");
}
});
The registerResults function was a namespace function based on the formatting, but you only need a standard function like the below.
$(document).ready(function () {
$('#registerForm').submit(function () {
var formData = $('#registerForm').serialize();
$.post('/admin/user/signup', formData, registerResults);
});
function registerResults() {
console.log("register success!");
} // end of registerResults
}); // end of ready