I want make a form with error message if the name already exist or group not exist.
I have the error message from the server when I click on submit .
Now I close the dialog box with the on Close Confirm function.
<button mat-raised-button class="createUserBtn" color="primary" type="submit" [disabled]="form.invalid" (click)="onCloseConfirm()">Save</button>
But now I have to click on save button , wait for the error message or not
If message , display it and let the dialog open.
If no error message , execute the function on Close Confirm.
the problem I think I have , is async wait , I wait for server answer to check error or not and after close or not the dialog.
this is my function Submit
error = false;
errorMessage = '';
onSubmit() {
if (this.form.valid) {
this.fixtureService.create(this.form.value)
.catch(error => {
console.log(error);
if (error.error.error ==='FIXTURE_NAME_TAKEN') {
console.warn("Fixture name already exist");
this.error = true;
this.errorMessage = 'Fixture name already exist'
} else if (error.error.error ==='GROUP_NOT_FOUND') {
console.warn("Group selected doesn't exist");
this.error = true;
this.errorMessage = 'Group selected doesn\'t exist'
} else onCloseConfirm();
}
Related
this project uses js , mongoose , node.js
if use an email that already exists during registration to create an account, it will refresh the page clear all fields and shows a pop up message using ajax that says email exists. i dont want the fields to be cleared
im trying to fix this. the idea that i thought would be perfect is if i can use an event listener that will check the email against the database every time the user types something in the email input field. i already did this with js to make sure the passwords are identical before posting, all help and tips and remarks are welcome
here is the part of the code that checks if email exists
module.exports.signUp = async (req, res) => {
const { site_web, username, fonction, direction, email} = req.body
try {
if(email){
var check = await InscritModel.findOne({ email: email });
if(check){
res.render('inscription', { layout: 'inscription', email: true});
}
else{
// create user
}
}
}
}
UPDATE
im still stuck with this, i trying to use ajax to constantly check the email input against the database in real time, but i know im messing up a lot of things,
i created a post route in user-routes called router.post("/emailCheck", emailCheck); and in function-controller file i created this function
module.exports.emailCheck = async (email) => {
var check = await InscritModel.findOne({ email: email });
if(check){
return 1;
}
else{
return 0;}
}
this is the html input call
<input type="email" id="txtUserEmail" class="form-control" name="email" placeholder="Email.." required>
and this is the crazy ajax code
$(document).ready(function () {
$('#txtUserEmail').keyup(function () {
var email = $(this).val();
if (email.length >= 3) {
$.ajax({
url: '/emailCheck',
method: 'post',
data: { email: email },
success: function (data) {
var divElement = $('#divOutput');
if (data) {
divElement.text(' already in use');
divElement.css('color', 'red');
}
else {
divElement.text( ' available')
divElement.css('color', 'green');
}
},
error: function (err) {
alert(err);
}
});
}
});
});
its shows a one very long error message with so many things, it ends with this
Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 8)
hopefuly ill get there, any help is appreciated, the idea i have in mind is to make ajax call a function that takes an email in its parameters and checks it against the database and returns true or false.
well, i ended up finding the solution, ill share for future people.
the goal: stop the other fields from getting cleared when the email already exists in database
the problem: verifying the email happens after the form is submit, which means the page gets refreshed
solution idea: disable the submit button, use js to listen on the email input, and verify the input against the database while the user is typing.
app.js or routes.js whatever u named it
const InscritModel = require('../models/inscrit-model');
router.get('/usercheck', function(req, res) {
console.log(req.query);
// dont forget to import the user model and change InscritModel by whatever you used
InscritModel.findOne({email: req.query.email} , function(err, InscritModel){
if(err) {
console.log(err);
}
var message;
if(InscritModel) {
console.log(InscritModel)
message = "user exists";
console.log(message)
} else {
message= "user doesn't exist";
console.log(message)
}
res.json({message: message});
});
});
in html
<div id="divOutput"></div>
<input type="email" id="usercheck" required>
<input type="submit" id="btsubmit" disabled />
in JS
$('#usercheck').on('keyup', function () {
console.log("ok");
console.log($(this).val().toLowerCase());
$.get('/usercheck?email=' + $(this).val().toLowerCase(), function (response) {
$('#divOutput').text(response.message);
var bouton = document.getElementById('btsubmit');
bouton.disabled = true;
if ($('#divOutput').html() === "user exists") {
$('#divOutput').text('Email not available').css('color', 'red');
}
else {
$('#divOutput').text('Email available').css('color', 'green');
bouton.disabled = false;
}
})
});
I want to redirect to the homepage and flash a message using flask, and I think I need to disable the preventDefault() function:
login_form.addEventListener("submit", (event) => {
event.preventDefault();
axios.post(login_form.action, {
username: login_form.username.value,
password: login_form.pass.value
}).then((response) => {
if (response.data["returnval"] === "wrong-crd")
{
_alert.innerHTML = "Username or password is incorrect";
_alert.hidden = false;
}
else
{
window.location.href = "/";
}
});
});
The code works but I can't flash a message, how can I disable the preventDefault() function.
My flask code:
#app.route("/login", methods=["GET", "POST"])
def login():
if request.method == "GET":
return render_template("login.html")
else:
username = request.json.get("username")
password = request.json.get("password")
cursor.execute("SELECT * FROM Users WHERE username = %s", (username,))
returned = cursor.fetchall()
if len(returned) == 0:
return jsonify(returnval="wrong-crd")
if check_password_hash(returned[0][3], password):
session.permanent = True
session["userId"] = returned[0][0]
flash("Logged in!")
return redirect("/")
else:
return jsonify(returnval="wrong-crd")
Since AJAX is asynchronous, it means that it takes time to get the response after you submit your request.
If you do not prevent default event on the start, it will usually trigger that default event BEFORE you even receive your response.
You can do something like this :
Make a function that will make a popup message, something like this :
function pushNotification(message){
alert(message);
}
We are going to be using localStorage to store popup messages that need to be shown.
So firstly we are going to add a small code to your main javascript file that will trigger the function that we just made :
let nextMSG = localStorage['nextMessage'];
if(nextMSG!=undefined && nextMSG!=""){
pushNotification(nextMSG);
localStorage['nextMessage']="";
}
Now all you have to do is modify your code so that :
a) - When the response fails(user doesn't log in), you call pushNotification() function directly
b) - When the user logs in, you firstly change value of localStorage['nextMessage'] to a value that you want the user to see after redirect, and then redirect the user to wanted location.
You could just call login_form.submit() to proceed with the default submission if the field values are correct.
login_form.addEventListener("submit", (event) => {
event.preventDefault();
axios.post(login_form.action, {
username: login_form.username.value,
password: login_form.pass.value
}).then((response) => {
if (response.data["returnval"] === "wrong-crd")
{
_alert.innerHTML = "Username or password is incorrect";
_alert.hidden = false;
}
else
{
login_form.submit();
}
});
});
How can I go about adding the value of an input box into an array and then display the contents of that array?
This is what I've come up with and I'm not sure why it's not working - the console.log doesn't post anything to the console, either.
var user = user;
if (!user) {
user = prompt('Please choose a username:');
if (!user) {
alert('Your name has been set to "Anonymous"');
} else {
alert('Your name has been set to "'+ user +'"');
}
}
var items = [];
function userArray() {
items.push(user);
return false;
console.log(items);
}
socket.on('onlineUsers', function (data) {
$('.dispUser').html(items);
});
The rest of the code in the file is below, just in case it helps... (changed the return statement, as per the first answer)
var user = user;
if (!user) {
user = prompt('Please choose a username:');
if (!user) {
alert('Your name has been set to "Anonymous"');
} else {
alert('Your name has been set to "'+ user +'"');
}
}
var items = [];
function userArray() {
items.push(users);
console.log(items);
return false;
}
socket.on('onlineUsers', function (data) {
$('.dispUser').html(items);
});
//Counts the number of users online
socket.on('count', function (data) {
$('.user-count').html(data);
});
//Receives messages and outputs it to the chat section
socket.on('message', function (data) {
$('.chat').append('<p><strong>' + data.user + '</strong>: ' + data.message + '</p>');
$('.chat').scrollTop($('.chat').height());
});
//SENDING OF THE MESSAGE
//Submit the form through HTTPS
$('form').submit(function (e) {
e.preventDefault();
// Retrieve the message from the user
var message = $(e.target).find('input').val();
// Send the message to the server
socket.emit('message', {
user: user || 'Anonymous',
message: message
});
// Clears the message box after the message has been sent
e.target.reset();
$(e.target).find('input').focus();
});
Answer
Your implementation is fine, but you have a bug which is preventing it from working as you've described.
The call to console.log(items) does not print anything, because that line of code never runs.
When you return from a function, the subsequent lines of code will not be ran. You should return as the last line within your function, or wrap it in a conditional.
For example:
function userArray() {
items.push(user);
console.log(items);
return false;
}
How to debug
Learning the techniques to figure this issue out yourself is an invaluable tool. You can leverage a debugger, such as the Chrome Devtools, to add breakpoints to your code. These will allow you to stop execution on a particular line, view the value of variables, and step through the remaining lines of code.
Doing so would make it clearly visible that the line of code is never running.
Find more details here: https://developers.google.com/web/tools/chrome-devtools/javascript
On the server-side I have a transaction which returns a JsonResult:
public JsonResult DoStuff(Guid id, string userInputText)
{
var product = _repository.Product(id); //busines logic
//Only a specific product must have userInputText <= 10 characters.
//Other products may have as many characters as the user wants.
if(product == Enum.SpecificProduct && userInputText.Count() > 10)
{
//The user input text comes from the View...
//If it has more then 10 characters, need to send the errorMessage to the View.
return Json(new { success = false, errorMessage = "error message" }, JsonRequestBehavior.AllowGet);
}
//Otherwise, do stuff on the product...
//and return success at the end.
return Json(new { success = true });
}
On the other hand, on the client-side I have this:
using (Ajax.BeginForm("DoStuff", ajaxOptions))
{
<span>Enter the text:</span>
#Html.TextArea("userInputText", new { onkeyup = "SyncContents(); return false;" })
<input type="submit" value="Add" />
<!-- error message should be displayed here-->
}
This is the AjaxOptions:
var ajaxOptions= new AjaxOptions
{
OnSuccess = "reload",
OnFailure = "FailMessage"
};
If the entered text have more then 10 characters, when the "Add" button is pressed, the Controller is being executing the code on the server-side and fails, how can I get the errorMessage from there and use it here, in the View, to inform the user ?
I tried to alert a message:
<script>
function FailMessage() {
alert("Fail Post");
}
</script>
But no pop-up "Fail post" appears.
Best regards.
The problem here is the Ajax helper thinks all your responses are successful. Your controller action is returning HTTP 200 so there isn't a problem.
https://msdn.microsoft.com/en-us/library/system.web.mvc.ajax.ajaxoptions.onfailure(v=vs.118).aspx#P:System.Web.Mvc.Ajax.AjaxOptions.OnFailure
AjaxOptions.OnFailure Property
This function is called if the response status is not in the 200 range.
So you'll need to use the success handler and explicitly check the JSON success parameter.
Or have your action change the HttpStatusCode for the response.
if (notValid)
{
Response.StatusCode = 400; // Bad Request
return Json(new { success = false, errorMessage = "error message" }, JsonRequestBehavior.AllowGet);
}
But for a validation error here I'd just check the for an error in the success handler.
And yes, you should validate on the client and on the server.
I have a function that will return an alert if the form was not filled out "error has occured" and if all fields are completed then the alert is "Form submitted successfully". My problem is that if there is an error then the alert "error has occured" fires and when I fill out the incomplete fields and submit the form the "error has occured" fires again because it already exists on the page. How do I ignore any current errors that were already alerted or clear current error alerts so that I can try to validate the form again?
any help is greatly appreciated.
this is my form test page that was built in Salesforce Pardot: http://go.esri.com/l/82202/2016-05-09/2jzdrk
<script>
function submitVerify() {
var formError = document.querySelector("#pardot-form .errors").innerHTML;
if (formError === "Please correct the errors below:") {
alert("error has occured");
} else {
alert("Form submitted successfully");
}
}
</script>
Before alerting that there's an error, empty out your errors field, like this:
<script>
function submitVerify() {
var formError = document.querySelector("#pardot-form .errors").innerHTML;
if (formError === "Please correct the errors below:") {
alert("error has occured");
// <=== reset error message here
document.querySelector("#pardot-form .errors").innerHTML = null;
} else {
alert("Form submitted successfully");
}
}
</script>