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>
Related
This is my java script for Register page for web using firebase authentication.When i fill the email and password till Alert message Testing will execute but firebase.auth()..... it will not execute and the page will get refresh automatically.
var email=document.getElementById("inemail").value;
var password=document.getElementById("inpass").value;
var password1=document.getElementById("inpass1").value;
var lPassword=password.length;
var lPassword1=password1.length;
if(lPassword < 7)
{
alert("Password Should more than seven Charecter");
return;
}
else if(password!=password1){
alert("Correctly Enter the Password");
return;
}
else if(password==password1 || lPassword1==lPassword)
{
alert("Testing");
firebase.auth().createUserWithEmailAndPassword(email.toString(),password.toString()).catch(function(error) {
var errorCode = error.code;
var errorMessage = error.message;
if (errorCode == 'auth/weak-password') {
alert('The password is too weak.');
} else {
alert(errorMessage);
}
console.log(error);
});
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
var email = user.email;
alert("Sucessfully Created");
}
else {
alert("sorry Try again");
}
});
}
}
in This script have any errors?if it have error please help me to find-out.
As Ticherhaz explains in his comment, your need to use the then() method to detect when the Promise returned by the asynchronous createUserWithEmailAndPassword() method is fulfilled.
The following should do the trick:
firebase.auth().createUserWithEmailAndPassword(email.toString(),password.toString())
.then(userCredential => {
var email = userCredential.user.email;
alert("Sucessfully Created");
})
.catch(function(error) {
var errorCode = error.code;
var errorMessage = error.message;
if (errorCode == 'auth/weak-password') {
alert('The password is too weak.');
} else {
alert(errorMessage);
}
console.log(error);
});
}
Note that, as explained in the doc, "on successful creation of the user account, this user will also be signed in to your application", so you don't need to use the onAuthStateChanged() method in this case.
In one of your comments above you say "only till alert message 'testing' this script is executing". Actually, if there is no error with the new user creation, the rejection handler callback passed to catch() is not called and therefore you don't get a feedback on the fact that the createUserWithEmailAndPassword() was correctly executed. For that you need the then() method.
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();
}
After validating my form with javascript I can not get it to submit to the server
myForm.addEventListener("submit", validation);
function validation(e) {
let data = {};
e.preventDefault();
errors.forEach(function(item) {
item.classList.add("cart__hide");
});
at the end of the validation I have the following code
if (!error) {
myForm.submit();
}
I also tried
if (error = false) {
myForm.submit();
}
if ((error == false)) {
myForm.submit();
}
when I console log error I am getting all false so the form should submit.
I am getting the following console log error
TypeError: myForm.submit is not a function
I did this same validation on an html page and it worked fine. Now I am trying to get it to work on a PHP page and it will not submit.
I am not sure why the myForm.submit() is causing the error.
Thanks
Jon
Remove e.preventDefault(); from your code and put it in your validation function like this:
if (error) {
e.preventDefault();
}
What you need to do is to only call Event#preventDefault when there is an error.
myForm.addEventListener("submit", validation);
function validation(e) {
var error = !form.checkValidity(); // replace this with the actual validation
if (error) e.preventDefault();
}
<form>
<input type="text">
<input type="submit" value="submit">
</form>
Howdie do,
I have a form that simply takes a username and email from a user. The input is sanitiazed via client and on the server side.
The script is sending the POST with no issue and it's returning the data as it should be as I've checked in the log. However, for some reason, the data isn't being displayed in the browser.
Code is below and I feel it's a stupid item I'm overlooking, but I can't find it anywhere
<!DOCTYPE HTML>
<HEAD>
<TITLE>Jeremy's Form Submit Test </TITLE>
<script type="text/javascript" src="js/jquery-1.11.2.js"></script>
<script>
$(document).ready(function()
{
$("#FormSubmit").click(function() //Set click action on formsubmit button
{
var submit = true;
$('#MainForm input[type="text"]').each(function() //Loop through input fields to ensure data is present
{
if($.trim($('#User').val()) == '') //Remove whitespaces and check if field is empty
{
alert('Input can not be blank');
submit = false;
}
var regex = /^[\w-\.]+#([\w-]+\.)+[\w-]{2,4}$/; //RegEx to test email against
if(!regex.test($.trim($('#Email').val()))) //If supplied email without whitespaces doesn't match pattern, then alert user
{
alert('Please provide a valid email');
submit = false;
}
});
if(submit == true) //If data is present, then prepare email and user values to be submitted to .php page
{
data = {'user_name': $('#User').val(), 'email': $('#Email').val()}; //Add username and email to array
$.post("success.php", data, function(ReturnedData) //post data via ajx to success.php and retrieve response
{
console.log(JSON.stringify(ReturnedData));
if(ReturnedData.Type == 'Error') //If error returned, display error message
{
var results = '<h1>'+ReturnedData.Message+'</h1>';
}
else if(ReturnedData.Type == 'Success') //If success returned, display message and remove submit button
{
var results = '<h1>'+ReturnedData.Message+'</h1>';
$('#FormSubmit').remove();
}
$('div#DataHolder').html(results);
}, 'json');
}
});
});
</script>
</HEAD>
<BODY>
<form id="MainForm">
*UserName: <input type="text" id="User" name="FormUsername" required />
*Email: <input type="email" id="Email" name="FormEmail" required />
<input type="submit" id="FormSubmit" value="Submit">
</form>
<div id="DataHolder"></div>
</BODY>
</HTML>
The PHP file is below that returns a json_encoded response and I've confirmed via the console log that the data is being returned properly, but it's not displaying in the div I've set. The log file is showing the correct response, but it's not displaying:
{"Type":"Error","Message":"UserName must be at least 3 characters!!!"}
<?php
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') //Check apache header to ensure its a json request
{
$ReturnedData = json_encode(array("Type" => "Error", "Message" => "Naughty naughty. This wasn't an ajax request"));
die($ReturnedData);
}
if(isset($_POST)) //Ensure that POST is set
{
//Santiaze the post variables to be double sure no one is up to any funky business
$SaniUser = filter_var($_POST['user_name'],FILTER_SANITIZE_STRING);
$SaniEmail = filter_var($_POST['email'],FILTER_SANITIZE_EMAIL);
//Check that username is at least 3 characters and return error if it's not
if(strlen($SaniUser) != 3)
{
$ReturnedData = json_encode(array("Type" => "Error", "Message" => "UserName must be at least 3 characters!!!"));
die($ReturnedData);
}
//Check that email is a valid email
if(!filter_var($SaniEmail,FILTER_VALIDATE_EMAIL))
{
$ReturnedData = json_encode(array("Type" => "Error", "Message" => "Please supply a valid email address!!!"));
die($ReturnedData);
}
//All variables are good. Return successfully message
$ReturnedData = json_encode(array("Type" => "Success", "Message" => "SUCCESS!!!" .$SaniUser. "Has successfully submitted the form"));
die($ReturnedData);
}
else
{
$ReturnedData = json_encode(array("Type" => "Error", "Message" => "Naughty naughty. No data was submitted!!!"));
die($ReturnedData);
}
?>
WOWOWOW the issue was staring me right in the face.
I didn't initialize var results initially when the data is present. So when I called .html(results), the result variable scope was only in the if/else statement.
Setting the variable at the top of the if statement and then setting the returnedData to that value works
Updated code is below:
if(submit == true) //If data is present, then prepare email and user values to be submitted to .php page
{
var results;
data = {'user_name': $('#User').val(), 'email': $('#Email').val()}; //Add username and email to array
$.post("success.php", data, function(ReturnedData) //post data via ajx to success.php and retrieve response
{
console.log(JSON.stringify(ReturnedData));
if(ReturnedData.Type == 'Error') //If error returned, display error message
{
results = '<h1>'+ReturnedData.Message+'</h1>';
//alert(ReturnedData.Message);
}
else if(ReturnedData.Type == 'Success') //If success returned, display message and remove submit button
{
$('#FormSubmit').hide();
results = '<h1>'+ReturnedData.Message+'</h1>';
}
$('#DataHolder').html(results);
}, 'json');
}
Ive been trying to get my submit button to return false if there are any error in my code, but it keeps bringing me to a broken page, i have tried in the console of firefox and there are no errors. Thanks
the return false is at the bottom
Code:
function searchForm(){
//checks all the boxes to see if there are any errors
confirmFName();
confirmLName();
confirmEmail();
confirmAddress1();
confirmAddress2();
confirmCity();
confirmCode();
confirmUName();
confirmPass();
//check to make sure a region is selected
if(nhlForm.regBox == "Choose a Country first", "Choose your Country First"){
//shows error message
showMessage(nhlForm.regBox, "error", "*Choose a region");
showMessage(nhlForm.counBox, "error", "*Choose a country");
}
//checks if checkbox is checked, if not messgae will appear and form will not send
if(nhlForm.agebox.checked == true){
showMessage(nhlForm.agebox, "bingo", "");
}else{
//shows error message
showMessage(nhlForm.agebox, "error", "You must be at least 14 to have an account");
}
if(nhlForm.checkbox.checked == true){
showMessage(nhlForm.checkbox, "bingo", "");
}else{
//shows error message
showMessage(nhlForm.checkbox, "error", "You must accept the terms of use to continue");
}
//if there are no errors, form will send
if(document.querySelectorAll(".error").length > 0){
//dont submit the form till errors are fixed
return false;
}
}
Try this code
function searchForm(){
//checks all the boxes to see if there are any errors
confirmFName();
confirmLName();
confirmEmail();
confirmAddress1();
confirmAddress2();
confirmCity();
confirmCode();
confirmUName();
confirmPass();
var flag=true;
//check to make sure a region is selected
if(nhlForm.regBox == "Choose a Country first", "Choose your Country First"){
//shows error message
showMessage(nhlForm.regBox, "error", "*Choose a region");
showMessage(nhlForm.counBox, "error", "*Choose a country");
flag=false;
}
//checks if checkbox is checked, if not messgae will appear and form will not send
if(nhlForm.agebox.checked == true){
showMessage(nhlForm.agebox, "bingo", "");
}else{
//shows error message
showMessage(nhlForm.agebox, "error", "You must be at least 14 to have an account");
flag=false;
}
if(nhlForm.checkbox.checked == true){
showMessage(nhlForm.checkbox, "bingo", "");
}else{
//shows error message
showMessage(nhlForm.checkbox, "error", "You must accept the terms of use to continue");
flag=false;
}
return flag;
}
and onSubmit="return searchForm()" in form tag