I am using a ajax-driven contact form and receive the error "ReferenceError: slickcontactparse is not defined".
Am not sure how to declare the function. Please help!!
js
$(document).ready(function(){
$('#slickform').submit(
function slickcontactparse() {
// EMAIL VALIDATION FUNCTION
var emailReg = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(#\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
// EDIT THIS SECTION IF DIFFERENT FORM ELEMENTS
// Values
var successmessage = "Thank you for email, we will be in contact soon!";
var failedmessage = "There was a problem, please try again!";
var usersname = $('#name');
var usersemail = $('#email');
var usersphone = $('#phone');
var userssubject = $('#subject');
var userscomment = $('#comment');
var usershuman = $('#human');
var isvalid = 1;
var url = "slickform.php";
//Checking information is correct before sending data
//CHECKING EMAIL IS PRESENT AND IS VALID
if (usersemail.val() == "") {
$(".slickbutton").animate({marginTop:'50px'},1000).delay(6000).animate({marginTop:'0px'},1000);
$(".errorcontainer").html('Please Insert Your Email!');
$(".errorcontainer").delay(1200).fadeIn(1000).delay(4000).fadeOut(1000);
$('input[type=submit]', $("#slickform")).removeAttr('disabled');
return false;
}
var valid = emailReg.test(usersemail.val());
if(!valid) {
$(".slickbutton").animate({marginTop:'50px'},1000).delay(6000).animate({marginTop:'0px'},1000);
$(".errorcontainer").html('Please Enter A Valid Email!');
$(".errorcontainer").delay(1200).fadeIn(1000).delay(4000).fadeOut(1000);
$('input[type=submit]', $("#slickform")).removeAttr('disabled');
return false;
}
//CHECKING EMAIL IS PRESENT AND IS VALID
//CHECKING USERS NAME IS PRESENT
if (usersname.val() == "") {
$(".slickbutton").animate({marginTop:'50px'},1000).delay(6000).animate({marginTop:'0px'},1000);
$(".errorcontainer").html('Please Insert Your Name!');
$(".errorcontainer").delay(1200).fadeIn(1000).delay(4000).fadeOut(1000);
$('input[type=submit]', $("#slickform")).removeAttr('disabled');
return false;
}
//CHECKING USERS NAME IS PRESENT
//CHECKING USERS PHONE NUMBER IS PRESENT AND IS ONLY NUMERIC
if (usersphone.val() == "") {
$(".slickbutton").animate({marginTop:'50px'},1000).delay(6000).animate({marginTop:'0px'},1000);
$(".errorcontainer").html('Please Insert Your Phone Number!');
$(".errorcontainer").delay(1200).fadeIn(1000).delay(4000).fadeOut(1000);
$('input[type=submit]', $("#slickform")).removeAttr('disabled');
return false;
}
var EnteredValue = $.trim(usersphone.val());
var TestValue = EnteredValue.replace(" ", "");
if (isNaN(TestValue)) {
$(".slickbutton").animate({marginTop:'50px'},1000).delay(6000).animate({marginTop:'0px'},1000);
$(".errorcontainer").html('Please Enter A Valid Phone Number!');
$(".errorcontainer").delay(1200).fadeIn(1000).delay(4000).fadeOut(1000);
$('input[type=submit]', $("#slickform")).removeAttr('disabled');
return false;
}
//CHECKING USERS NAME IS PRESENT
//CHECKING SUBJECT WAS SELECTED
if (userssubject.val() == "") {
$(".slickbutton").animate({marginTop:'50px'},1000).delay(6000).animate({marginTop:'0px'},1000);
$(".errorcontainer").html('Please Select A Subject!');
$(".errorcontainer").delay(1200).fadeIn(1000).delay(4000).fadeOut(1000);
$('input[type=submit]', $("#slickform")).removeAttr('disabled');
return false;
}
//CHECKING SUBJECT WAS SELECTED
//CHECKING THE USER IS HUMAN
if (usershuman.val() != 15) {
$(".slickbutton").animate({marginTop:'50px'},1000).delay(6000).animate({marginTop:'0px'},1000);
$(".errorcontainer").html('Your Are You Human Math Is Incorrect!');
$(".errorcontainer").delay(1200).fadeIn(1000).delay(4000).fadeOut(1000);
$('input[type=submit]', $("#slickform")).removeAttr('disabled');
return false;
}
//CHECKING THE USER IS HUMAN
//CHECKING THE USER IS HUMAN
if (userscomment.val() == "") {
$(".slickbutton").animate({marginTop:'50px'},1000).delay(6000).animate({marginTop:'0px'},1000);
$(".errorcontainer").html('You Forgot To Leave A Message!');
$(".errorcontainer").delay(1200).fadeIn(1000).delay(4000).fadeOut(1000);
$('input[type=submit]', $("#slickform")).removeAttr('disabled');
return false;
}
//CHECKING THE USER IS HUMAN
/*
*
* POSTING DATA USING AJAX AND
* THEN RETREIVING DATA FROM PHP SCRIPT
*
*/
$.post(url,{ usersname: usersname.val(), usersemail: usersemail.val(), usersphone: usersphone.val(), userssubject: userssubject.val(), userscomment: userscomment.val(), usershuman: usershuman.val(), isvalid: isvalid } , function(data) {
if(data == 'success'){
$(".slickbutton").animate({marginTop:'50px'},1000).delay(6000).animate({marginTop:'0px'},1000);
$(".successcontainer").html(successmessage);
$(".successcontainer").delay(1200).fadeIn(1000).delay(4000).fadeOut(1000);
$("#name").val('');
$("#email").val('');
$("#phone").val('');
$("#subject").val('');
$("#comment").val('');
$("#human").val('');
$('input[type=submit]', $("#slickform")).removeAttr('disabled');
} else {
$(".slickbutton").animate({marginTop:'50px'},1000).delay(6000).animate({marginTop:'0px'},1000);
$(".errorcontainer").html(failedmessage);
$(".errorcontainer").delay(1200).fadeIn(1000).delay(4000).fadeOut(1000);
$('input[type=submit]', $("#slickform")).removeAttr('disabled');
return false;
}
});
}
);
});
Here's the php:
if(isset($_REQUEST["isvalid"])){
$youremail = "test#test.com";
$usersname = $_POST["usersname"];
$usersemail = $_POST["usersemail"];
$usersphonenumber = $_POST["usersphone"];
$mailsubject = "Contact From Your Slickform";
$subject = $_POST["userssubject"];
$usersmessage = $_POST["userscomment"];
$message =
"$usersname has contacted you from your site.
$subject:
Their Message is as follows:
$usersmessage
...............................................
Contact details:
Phone Number: $usersphonenumber
Email Address: $usersemail";
$headers = 'From:' . $usersemail . "\r\n";
mail($youremail, $mailsubject, $message, $headers);
echo "success";
} else {
echo "failed";
}
Any help is appreciated. Thank you!
Either do this:
$('#slickform').submit(function() { // remove the callback fn name
or make a global function and use it like this:
slickcontactparse() {
// all your code
}
$(document).ready(function(){
$('#slickform').submit(slickcontactparse); // call it here as callback
});
Related
I am creating a login form which is limited to only 3 attempts then redirects the user. However, it quickly iterates from 3 to 0 at only 1 failed try then redirects the user. I have been trying but have been stuck at this.
Javascript loginUser code which runs upon submit:
function loginUser() {
var form = document.getElementById("myForm");
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
google.script.run.withSuccessHandler(function(output) {
var atmp = 3;
while(atmp > 0) {
if(output == 'TRUE') {
console.log("Success");
form.reset();
break;
}
else if (output == 'FALSE') {
console.log("Denied");
atmp--;
form.reset();
Swal.fire({
icon: 'error',
title: 'Wrong Username/Password! Please, try again.',
showCancelButton: false,
});
}
} if (atmp == 0) {
console.log("3 Failed attempts!");
// Redirect code here...
}
}).checkLogin(username, password);
}
Code.gs checkLogin function:
function checkLogin(username, password) {
var url = 'sheetLinkHere';
var ss= SpreadsheetApp.openByUrl(url);
var webAppSheet = ss.getSheetByName("users");
var find = webAppSheet.getDataRange().getDisplayValues().find(([, , c, d]) => c == username && d == password);
return find ? 'TRUE' : 'FALSE';
}
I tried placing the while loop at different parts of the code but still wont work for me.
I was finally able to fix it. Credits to #Ruben in the comment section for giving me an idea. I just placed the variable outside the function and used an if-statement instead.
var atmp = 2;
function loginUser() {
var form = document.getElementById("myForm");
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
google.script.run.withSuccessHandler(function(output) {
if(atmp == 0) {
//redirect code here...
}else if(atmp > 0) {
if(output == 'TRUE') {
console.log("Success");
form.reset();
}
else if (output == 'FALSE') {
console.log("Denied");
atmp--;
}
}
}).checkLogin(username, password);
}
I think you're trying to do something like this:
const
realPassword = "Melon",
input = document.querySelector('input'),
feedback = document.querySelector('span');
input.addEventListener('change', handlePasswordAttempt);
input.focus();
let attempts = 3;
function handlePasswordAttempt(event){
--attempts;
const attemptedPassword = input.value;
input.value = "";
input.focus();
if(attempts == 0){
feedback.textContent = "No login for you!";
input.setAttribute("disabled", "");
}
else if(attemptedPassword == realPassword){
feedback.textContent = "Qapla'!";
input.setAttribute("disabled", "");
}
else{
feedback.textContent = `Incorrect password. ${attempts} tries left.`;
}
}
<div>Enter password:<input></div><br/>
<div><span></span></div>
We have a Shopify store and i have a script which validates the email adress and writes out if the email address is not good, another script is checking if the form is filled out and if it's not - it's not letting the customer to pass the next stage based on ID selector.
I only need this email validator to do the same thing as the other script, write out an alert when the email address is not correct and don't let them pass to the next step.
Can someone help with this? How to do that?
Script which validates the email address:
const validateEmail = (email) => {
return email.match(
/^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
);
};
const validate = () => {
const $result = $('#result');
const email = $('#email').val();
$result.text('');
if (validateEmail(email)) {
$result.text(email + ' e-mail address is valid!');
$result.css('color', 'green');
} else {
$result.text(email + ' Lūdzu, ievadiet derīgu e-pastu lai pabeigt pirkumu');
$result.css('color', 'red');
}
return false;
}
$('#email').on('input', validate);
Script which checks wheter the form was filled out or not:
document.getElementById("cart__checkout").onclick = function() {
let allAreFilled = true;
document.getElementById("myForm").querySelectorAll("[required]").forEach(function(i) {
if (!allAreFilled) return;
if (i.type === "radio") {
let radioValueCheck = false;
document.getElementById("myForm").querySelectorAll(`[name=${i.name}]`).forEach(function(r) {
if (r.checked) radioValueCheck = true;
})
allAreFilled = radioValueCheck;
return;
}
if (!i.value) { allAreFilled = false; return; }
})
if (!allAreFilled) {
alert('Lūdzu, ievadiet Jūsu e-pastu lai pabeigt pirkumu!');
}
};
Appreciate the help, what i'm missing here?
Thank you!
Use the email validation inside on onClick event like this and set the var allAreFilled false is email validation failed
document.getElementById("cart__checkout").onclick = function() {
let allAreFilled = true;
document.getElementById("myForm").querySelectorAll("[required]").forEach(function(i) {
if (!allAreFilled) return;
if (i.type === "radio") {
let radioValueCheck = false;
document.getElementById("myForm").querySelectorAll(`[name=${i.name}]`).forEach(function(r) {
if (r.checked) radioValueCheck = true;
})
allAreFilled = radioValueCheck;
return;
}
if (!i.value) { allAreFilled = false; return; }
});
/* Here email valdation */
const email = $('#email').val();
if( !email.match(
/^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
)){
allAreFilled = false;
}
/* terms and condtions check */
if( !$('#CartTermsDrawer').is(':checked') ){
allAreFilled = false;
}
if (!allAreFilled) {
alert('Lūdzu, ievadiet Jūsu e-pastu lai pabeigt pirkumu!');
return;
}
};
I have stored username and password to a key login in local storage and I need to validate from home page using JavaScript code.
function validlogin(event)
function validlogin(event) {
var user = document.getElementById('user').value;
var psw = document.getElementById('psw').value;
var entriesJSON = localStorage.getItem('login');
if (!entriesJSON) {
alert("Nothing stored!");
event.preventDefault();
return;
}
var allEntries = JSON.parse(entriesJSON);
for (var i = 0; i < login.length; i++) {
var entry = login[i];
var username = entry.user;
var password = entry.pass;
var email = entry.email;
if (user == storedUserName && psw == storedPassWord) {
alert("Successfully logged in!");
return;
}
alert('Invalid Username or Password! Please try again.');
event.preventDefault();
window.location = "test.html";
}
}
Just you have to add a else condition like below
if (user == storedUserName && psw == storedPassWord) {
alert("Successfully logged in!");
return;
}
else{
alert('Invalid Username or Password! Please try again.');
event.preventDefault();
window.location = "test.html";
}
If you're not using else condition, It definitely pass the if condition and says
alert("Successfully logged in!");
but after that it gives an
alert('Invalid Username or Password! Please try again.');
So just use else condition. And then all good. Good work champ ; )
function validlogin() {
var user = document.getElementById('user').value;
var psw = document.getElementById('psw').value;
var items = JSON.parse(localStorage.getItem('login'));
for (let i = 0; i < items.length; i++) {
if (items[i].username == user && items[i].password == psw)
{
alert("welcome");
}
}
}
I have an html form that is validated by Javascript, but since connecting to an external API the form submits before the API queries have returned
All of the alerts are triggering correctly, however the last line of code - if (rtn) {
$('#saleForm')[0].submit();
} -
is resolving before the api call data returns and therefore once I accept the alerts the form always submits (as rtn is always true).
I am using setTimeout to wait for the return in the two if() blocks, and have tried a do/whilst loop around submit but that didn't work.
Is there a method I can use to force the submit to wait until all the previous conditions have been checked, before if(rtn)?
$('#saleForm').off('submit').on('submit', function(e) {
e.stopPropagation();
e.preventDefault();
var rtn = true;
if (window.hasIntegration == 'no' && $('#eventDate').val() == '') {
alert('Please choose the event date and time.');
$('#eventDate').focus();
return false;
}
$('.itemValue').each(function() {
if ($(this).val() == '') {
alert('Please ensure all values are entered.');
$('#ticket-rows').focus();
rtn = false;
}
});
if (!$('#terms').is(':checked')) {
alert('Please accept the terms and conditions.');
return false;
}
// now use integration to validate user supplied details
if (window.integrationId == 2) {
window.foundApiSellerDetails = [];
window.sellerEmailMatch = [];
var apiShowSelected = document.getElementById("showDateTime");
var apiShowId = apiShowSelected.value;
var orderRefField = document.getElementById('order_reference');
var orderRef = orderRefField.value;
$.get('/' + id + '/api-seller-details/' + apiShowId + '/' + orderRef, function(data) {
if (data.length > 0) {
window.foundApiSellerDetails = 'yes';
$.each( data.result, function( key, value ) {
var apiOrderId = value.order.id;
var apiBuyerEmail = value.buyer.email;
var apiOrderToken = value.token;
$.get('/get-seller-email', function(data) {
if (apiBuyerEmail === data) {
window.sellerEmailMatch = 'yes';
} else {
window.sellerEmailMatch = 'no';
}
});
});
} else {
window.foundApiSellerDetails = 'no';
}
});
setTimeout(function(){
if (window.foundApiSellerDetails == 'no') {
alert('Sorry, we can\'t find any details with Order Reference ' + orderRef + '. Please check your order number or contact);
$('#order_reference').focus();
return false;
}
if (window.foundApiSellerDetails == 'yes' && window.sellerEmailMatch == 'no') {
alert('Sorry, your email doesn\'t match the buyers email for this order');
return false;
}
}, 1000);
}
if (rtn) {
$('#saleForm')[0].submit();
}
});
Thanks everybody! I have brought the submit function inside the setTimeout function, and then brought that whole block inside the $.get api call as per #Gendarme. I've also added else after the if integration == 2, to make the submit work if no integration exists. New code below. Works a treat now.
// now use integration to validate user supplied details
if (window.integrationId == 2) {
window.foundApiSellerDetails = [];
window.sellerEmailMatch = [];
var apiShowSelected = document.getElementById("showDateTime");
var apiShowId = apiShowSelected.value;
var orderRefField = document.getElementById('order_reference');
var orderRef = orderRefField.value;
$.get('/' + id + '/api-seller-details/' + apiShowId + '/' + orderRef, function(data) {
if (data.length > 0) {
window.foundApiSellerDetails = 'yes';
$.each( data.result, function( key, value ) {
var apiOrderId = value.order.id;
var apiBuyerEmail = value.buyer.email;
var apiOrderToken = value.token;
$.get('/get-seller-email', function(data) {
if (apiBuyerEmail === data) {
window.sellerEmailMatch = 'yes';
} else {
window.sellerEmailMatch = 'no';
}
});
});
} else {
window.foundApiSellerDetails = 'no';
}
setTimeout(function(){
if (window.foundApiSellerDetails == 'no') {
alert('Sorry, we can\'t find any details with Order Reference ' + orderRef + '. Please check your order number or contact);
$('#order_reference').focus();
return false;
}
if (window.foundApiSellerDetails == 'yes' && window.sellerEmailMatch == 'no') {
alert('Sorry, your email doesn\'t match the buyers email for this order');
return false;
}
if (rtn) {
$('#saleForm')[0].submit();
}
}, 1000);
});
} else {
if (rtn) {
$('#saleForm')[0].submit();
}
}
});
When someone put Greek characters in the NAME field on SEND the contact form returns with an error report.
So, how do I edit my validation form to accept Greek characters in both NAME & MESSAGE fields?
function validation() {
var contactname = document.forms["contactfrm"]["name"].value;
var name_exp = /^[A-Za-z\s]+$/;
if (contactname == '') {
swal("You forgot your name...", " ", "warning");
document.forms["contactfrm"]["name"].focus();
return false;
} else if (!contactname.match(name_exp)) {
swal("Invalid name...", " ", "error");
document.forms["contactfrm"]["name"].focus();
return false;
}
var email = document.forms["contactfrm"]["email"].value;
//var email_exp = /^[A-Za-z0-9\.-_\$]+#[A-Za-z]+\.[a-z]{2,4}$/;
var email_exp = /^\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
if (email == '') {
swal("You forgot to enter your email...", " ", "warning");
document.forms["contactfrm"]["email"].focus();
return false;
} else if (!email.match(email_exp)) {
swal("Your email address is invalid...", " ", "error");
document.forms["contactfrm"]["email"].focus();
return false;
}
var message = document.forms["contactfrm"]["comments"].value;
if (message == '') {
swal("No empty messages, please...", "warning");
document.forms["contactfrm"]["comments"].focus();
return false;
}
return true;
}
You can achieve this by changing the name expression to:
name_exp=/^[A-ZA-zΑ-Ωα-ωίϊΐάέήόύϋΰώΆΈΉΌΏΎΫ\s]+$/;
and email expression to:
//var email_exp=/^[A-Za-z0-9\.-_\$]+#[A-Za-z]+\.[a-z]{2,4}$/;
var email_exp=/^\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*$/;