Submit action using an automatic get method? - javascript

I am developing a wordpress plugin and am having a bit of trouble with my form submission. When activated the plugin essentially creates a little contact form with three fields so that a user would be able to enter in their name, email and phone number and then click submit which would then validate the code and store it in a database.
The strange thing is when clicking the Submit button the data seems to be sent using a get method as it is displayed in the url. I am handling the click of the button with an ajax post in a javascript file though. Here is the form code:
<div id="formwrapper" style="border:solid;border-color:red;">
<form name="contact" action="">
<label><strong>Contact Us</strong></label>
</br>
</br>
<input type="text" name="name" placeholder="Name & Surname">
<label class="error" for="name" id="nameErr">Please enter your name and surname</label>
</br>
</br>
<input type="email" name="email" placeholder="Email Address">
<label class="error" for="email" id="emailErr">Please enter a valid email address</label>
</br>
</br>
<input type="phone" name="phone" placeholder="Cell or Landline">
<label class="error" for="phone" id="phoneErr">Please enter your cell or landline number</label>
</br>
</br>
<input type="submit" class="button" name="submit" value="Submit" id="submit_button">
</form>
</div>
And this is the javascript I am using to handle the click of the button:
$(".button").click(function() {
$(".error").hide();
var name = $("input#name").val();
if (name == "") {
$("label#nameErr").show();
$("input#name").focus();
return false;
}
var email = $("input#email").val();
if (email == "") {
$("label#emailErr").show();
$("input#email").focus();
return false;
}
var phone = $("input#phone").val();
if (phone == "") {
$("label#phoneErr").show();
$("input#email").focus();
return false;
}
var datastring = 'name=' + name + '&email' + email + '&phone' + phone;
$.ajax({
type:"POST";,
url: "bin/process.php",
data: datastring,
success: function() {
$('#formwrapper').html("div id='message'></div>");
$('#message').html("<h2>Contact form submitted!</h2>")
.append("<p>We will be in touch soon.</p>").hide().fadeIn(1500, function() {
$('#message').append("<img id='checkmark' src='images/check.png' />");
});
}
});
alert "hello";
return false;
}
Not only does clicking the button not properly post the values, it seems to activate some sort of search function within wordpress as all the posts disappear and return with a "Sorry , no posts matched your criteria" message.

You have an error in your js code
alert "hello";
is not valid use:
alert("hello");
Due to this your return false does not get triggered and the form submits as normal.
Use event.preventDefault instead of returning false so that you will detect errors like this better
$(".button").click(function(e){
e.preventDefault();
...
});
And as Joe Frambach points out another syntax error is in your ajax options
type:"POST";,
should be
type:"POST",

try this
$(".button").click(function() {
$(".error").hide();
var name = $("input#name").val();
if (name == "") {
$("label#nameErr").show();
$("input#name").focus();
return false;
}
var email = $("input#email").val();
if (email == "") {
$("label#emailErr").show();
$("input#email").focus();
return false;
}
var phone = $("input#phone").val();
if (phone == "") {
$("label#phoneErr").show();
$("input#email").focus();
return false;
}
var datastring = 'name=' + name + '&email' + email + '&phone' + phone;
$.ajax({
type:"GET";,
url: "bin/process.php",
data: datastring,
success: function() {
$('#formwrapper').html("div id='message'></div>");
$('#message').html("<h2>Contact form submitted!</h2>")
.append("<p>We will be in touch soon.</p>").hide().fadeIn(1500, function() {
$('#message').append("<img id='checkmark' src='images/check.png' />");
});
}
});
alert "hello";
return false;
}

Related

Text obtained with innerHTML dissapear

I have the following code:
function passVerif() {
if (document.forms['form'].pass.value === "") {
messagePV.innerHTML = ("Password field is empty!")
//alert("Password field is empty!");
return false;
}
return true;
}
function emailVerif() {
if (document.forms['form'].email.value === "") {
messageEV.innerHTML = ("Email field is empty!")
//alert("Email field is empty!");
return false;
}
return true;
}
function validate() {
var email = document.getElementById("input").value;
var emailFilter = /^([a-zA-Z0-9_.-])+#(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
if (!emailFilter.test(email)) {
messageV.innerHTML = ("Please enter a valid e-mail address!")
//alert('Please enter a valid e-mail address!');
return false;
}
}
<div>
<form name="form"> Login<br>
<input type="text" name="email" placeholder="Enter email here" id="input" class="input">Email address<br>
<input type="password" name="pass" placeholder="Enter password here" class="input">Password<br>
<input type="button" name="required" onclick="return passVerif(), emailVerif(), validate()">
</form>
</div>
<div id="messagePV"></div>
<div id="messageEV"></div>
<div id="messageV"></div>
As you can see, input type is submit. Because of that (page is refreshing after click on button) the text I want to show disappears after refresh.
As I read on other posts, the simple change from submit to button will do the dew.
But I am suspecting that I messed up the return false and return true instructions in all of my functions.
Is this correct? If they are in a logical way I can avoid the page refresh and continue to use submit? At least until all conditions are met and the form is good to go.
In other words, can someone help me to put return false and true in such way that the page will refresh only if all conditions are met.
Thanks a lot, I am not even a noob.
Codes are copied from different sources on the internet. I am at the very beginning of coding road. Please have mercy :)
I would change it to one validation function and have a bool that is returned based on if it has errored or not:
// Just have one validation function
function validate() {
var errorMessage = ''; // build up an error message
var email = document.forms['form'].email.value;
var emailFilter = /^([a-zA-Z0-9_.-])+#(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
if (email === "") {
errorMessage += "Email field is empty!<br>";
} else if (!emailFilter.test(email)) { // this can be else if
errorMessage += "Please enter a valid e-mail address!<br>";
}
if (document.forms['form'].pass.value === "") {
errorMessage += "Password field is empty!<br>"
}
if (errorMessage === '') {
return true; // return true as no error message
} else {
document.getElementById('error-message').innerHTML = errorMessage; // show error message and return false
return false;
}
}
<div>
<form name="form"> Login<br>
<input type="text" name="email" placeholder="Enter email here" id="input" class="input">Email address<br>
<input type="password" name="pass" placeholder="Enter password here" class="input">Password<br>
<input type="submit" name="required" onclick="return validate();">
</form>
</div>
<div id="error-message">
<!-- CAN HAVE ONE ERROR MESSAGE DIV -->
</div>
I tried with your code and I could find the the messages were not getting updated based on the conditions. So I did few modifications to your code to display the message based on which condition fails.
HTML
<div>
<form name="form"> Login<br>
<input type="text" name="email" placeholder="Enter email here" id="input" class="input">Email address<br><br>
<input type="password" name="pass" placeholder="Enter password here" class="input">Password<br><br>
<input type="submit" name="required" value="Submit" onclick="return passVerif(), emailVerif(), validate()">
</form>
</div>
<div id="messagePV"></div>
<div id="messageEV"></div>
<div id="messageV"></div>
JS
function passVerif() {
messagePV.innerHTML = ("")
if(document.forms['form'].pass.value === "") {
messagePV.innerHTML = ("Password field is empty!")
//alert("Password field is empty!");
return false;
}
return true;
}
function emailVerif() {
messageEV.innerHTML = ("")
if(document.forms['form'].email.value === "") {
messageEV.innerHTML = ("Email field is empty!")
//alert("Email field is empty!");
return false;
}
return true;
}
function validate() {
messageV.innerHTML = ("")
var email = document.getElementById("input").value;
var emailFilter = /^([a-zA-Z0-9_.-])+#(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
if (!emailFilter.test(email)) {
messageV.innerHTML = ("Please enter a valid e-mail address!")
//alert('Please enter a valid e-mail address!');
return false;
}
}
By initializing the errormessage filed to empty sting u can maintain the fresh set of error messages.
Jsfiddle: https://jsfiddle.net/85w7qaqx/1/
Hope this helps out.

How to change errorMess value based on a condition in form-validator jquery plugin

I am trying to validate a form using jquery form validator plugin. I want to display custom messages like if the email is not given then it should display email address is required, if email value is not a valid one then it should display invalid email address. But in both cases, it is giving me the same default message like 'You have not given a correct e-mail address'. I tried to like this
<form action="" id="registration-form">
<p>E-mail
<input name="email" id="email" data-validation="email" >
</p>
<p>
<input type="submit" value="Validate">
<input type="reset" value="Reset form">
</p>
</form>
The script is
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery-form-validator/2.3.20/jquery.form-validator.min.js"></script>
$.validate({
onElementValidate : function(valid, $el, $form, errorMess) {
if ($el.attr('name') == 'email') {
alert('Input ' +$el.attr('name')+ ' is ' + ( valid ? 'VALID':'NOT VALID') );
var value = $('#email').val();
if (value) {
var filter=/^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i
if (! filter.test(value)) {
alert('invalid');
errorMess = 'invalid email';
}
} else {
alert('no mail');
errorMess = 'no email';
}
}
alert('errorMess :: ' + errorMess);
$('.help-block form-error').html(errorMess);
},
borderColorOnError: '#b94a48',
errorMessagePosition : 'inline',
modules : 'location, date, security, file',
onModulesLoaded : function() {
$('#country').suggestCountry();
}
});
It is pretty simple, adding multiple values in data-validation will actually done the magic.
<input name="email" id="email" data-validation="required, email" >

Form Validation in a pop up window

Hi I am displaying a pp up window based on the value stored in a localStorage.In the pop up window there is a form containing email and password.The user has to enter his email and password.Now what I need is that, the email entered by user has to be sent to a url and the url returns a status(either 1 or 0).If the url returns 1 then the user can just continue with the log in process.Otherwise an error message should be shown.The url is in the format http://www.calpinemate.com/employees/attendanceStatus/email/3".Here in the place of email highlighten should come the email entered by user in the form.In this way I have to pass the email.In this way I am doing form validation.But I don't know how to do.
Here is my userinfo.html
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="test.js"></script>
</head>
<body>
<b>Enter your Email ID and Password</b><br><br>
<form id="userinfo">
<label for="user"> Email : </label>
<input type="text" id="user" />
<br><br>
<label for="pass">Password : </label>
<input type="password" id="pass" />
<br>
<br>
<input type="button" id="login" value="Log In" />
</form>
</body>
</html>
This is the form in the pop up window
Here is my test.js
window.addEventListener('DOMContentLoaded', function() {
var user = document.querySelector('input#user');
var pwd = document.querySelector('input#pass');
var login = document.querySelector('input#login');
login.addEventListener('click', function() {
var userStr = user.value;
login();
window.close();
chrome.runtime.getBackgroundPage(function(bgPage) {
bgPage.updateIcon();
});
});
function login(){
var urlPrefix = 'http://www.calpinemate.com/employees/attendanceStatus/';
var urlSuffix = '/3';
var req = new XMLHttpRequest();
req.addEventListener("readystatechange", function() {
if (req.readyState == 4) {
if (req.status == 200) {
var item=req.responseText;
if(item==1){
localStorage.username=userStr;
localStorage.password=pwd;
}
else{ alert('error');}
}
}
});
var url = urlPrefix + encodeURIComponent(userStr) + urlSuffix;
req.open("GET", url);
req.send(null);
}
});
This is my javascript.When the user presses the log in button,whatever the user enters in the email textbox gets stored in localStorage.username.Now what I need is that I have to check whether such an email id exists by passing the email to the above specified url.And if it exists only it should be stored in localStorage.username.Please anyone help me. I have tried using the above code.But noting happens.Please help me
Here is a resource you can edit and use Download Source Code or see live demo here http://purpledesign.in/blog/pop-out-a-form-using-jquery-and-javascript/
It is a contact form. You can change it to validation.
Add a Button or link to your page like this
<p>click to open</p>
“#inline” here should be the “id” of the that will contain the form.
<div id="inline">
<h2>Send us a Message</h2>
<form id="contact" name="contact" action="#" method="post">
<label for="email">Your E-mail</label>
<input type="email" id="email" name="email" class="txt">
<br>
<label for="msg">Enter a Message</label>
<textarea id="msg" name="msg" class="txtarea"></textarea>
<button id="send">Send E-mail</button>
</form>
</div>
Include these script to listen of the event of click. If you have an action defined in your form you can use “preventDefault()” method
<script type="text/javascript">
$(document).ready(function() {
$(".modalbox").fancybox();
$("#contact").submit(function() { return false; });
$("#send").on("click", function(){
var emailval = $("#email").val();
var msgval = $("#msg").val();
var msglen = msgval.length;
var mailvalid = validateEmail(emailval);
if(mailvalid == false) {
$("#email").addClass("error");
}
else if(mailvalid == true){
$("#email").removeClass("error");
}
if(msglen < 4) {
$("#msg").addClass("error");
}
else if(msglen >= 4){
$("#msg").removeClass("error");
}
if(mailvalid == true && msglen >= 4) {
// if both validate we attempt to send the e-mail
// first we hide the submit btn so the user doesnt click twice
$("#send").replaceWith("<em>sending...</em>");
//This will post it to the php page
$.ajax({
type: 'POST',
url: 'sendmessage.php',
data: $("#contact").serialize(),
success: function(data) {
if(data == "true") {
$("#contact").fadeOut("fast", function(){
//Display a message on successful posting for 1 sec
$(this).before("<p><strong>Success! Your feedback has been sent, thanks :)</strong></p>");
setTimeout("$.fancybox.close()", 1000);
});
}
}
});
}
});
});
</script>
You can add anything you want to do in your PHP file.

form validation error

I have little problem with form and I am using js for validation.
Here is my form code.
<form method="get" onkeydown="checkEnter()" action="emailform.php" id="signupform" name="subscribe">
<input name="email" id="email" type="text" value="Enter Email for Updates" onfocus="if(this.value=='Enter Email for Updates'){this.value=''};" />
<input type="hidden" name="submitted" id="submitted" value="true" />
</form>
id signupform I am using for validation and submit the form is on pressing enter button.
But there is problem when put signupform then my validation start working fine and when I enter correct email it's show me error and when I remove the signupform id then my form submission work fine without validation.
Here is my JS code for id signupform.
function SubscribeForm() {
$('#signupform').submit(function () {
$('.email').removeClass('error')
$('em.error').remove();
var error = false;
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if ($.trim($('.email').val()) == '') {
$(this).append('<em class="error">Please enter your email address.</em>');
$(this).addClass('error');
error = true;
} else if (!emailReg.test(jQuery.trim($('.email').val()))) {
$(this).append('<em class="error">Please enter a valid email address</em>');
$(this).addClass('error');
error = true;
}
if (!error) {
$("#submit", this).after('<span id="form_loading"></span>');
var formValues = $(this).serialize();
$.post($(this).attr('action'), formValues, function (data) {
$("#signupform").before(data);
});
$(':input[type="text"]').attr('value', '');
}
return false
});
}
change
return false
to
return error;
it is causing problem.
change
return false;
to
return !error;
Also, add css class "email" to input email field, or change jquery to selector code ".email" to "#email"
Also a possible solution, if you don't need to support the old browser: placeholder.
<input placeholder="Enter email" type="text"... />
Thanks for your help Guys. i just put this and now working fine.
$('#signupform').submit(function(){
$('.email').removeClass('error')
$('em.error').remove();
var filter = /^([\w-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
sEmail = document.getElementById('email').value;
if (filter.test(sEmail)) {
return true;
}
else {
if(sEmail == '')
{
$(this).append('<em class="error">Please enter your email address</em>');
$(this).addClass('error');
}
else
{
$(this).append('<em class="error">Please enter a valid email address</em>');
$(this).addClass('error');
}
return false;
}
});
});

JS validation fails at normal speed but works when stepping through the code

js validation works perfectly when I step through it, but fails at "normal speed." SPECIFICALLY: if a dup email is caught but the other fields are filled in correctly, the form can be submitted (but no error is forthcoming when stepping through the code). Has anyone seen this before? I know I could just code it a different way, but I cannot simply walk away from this simple problem that's even become a bottle kneck without first understanding why this isn't working.
My approach is to validate onblur and onsubmit. I am using the jquery selector only for convenience and then again for an ajax call, but otherwise i'm using js. I am doing a loop through the fields but only operating on text and password fields.
checking for blanks
checking for no numbers in name
checking for email address properly formatted
and then checking for unique email in the email field
annotated code below for js and form below:
//registration validation
$('.validate').blur(function() {
var theForm = document.registerNewUserForm;
//removes error messages from html before the run
clearAllErrors(theForm);
var msg = "";
var mdiv;
theForm.submit.disabled=true;
document.getElementById("submitButton").disabled = true;
for (var i = 0; i < theForm.elements.length; i++) {
//mdiv is set to form element being evaluated at the time
mdiv = document.getElementById(theForm.elements[i].name + "Message");
msg = validateField(theForm.elements[i]);
if(msg != "") {
mdiv.innerHTML = msg;
break;
}
}
if(msg == "") {
theForm.submit.disabled=false;
document.getElementById("submitButton").disabled = false;
}
});
$('#registerNewUserForm').submit(function() {
var theForm = document.registerNewUserForm;
clearAllErrors(theForm);
var msg = "";
var mdiv;
for (var i = 0; i < theForm.elements.length; i++) {
//mdiv is set to form element being evaluated at the time
mdiv = document.getElementById(theForm.elements[i].name + "Message");
msg = validateField(theForm.elements[i]);
if(msg != "") {
break;
}
}
if (msg != ""){
mdiv.innerHTML = msg;
return false;
} else {
theForm.submit();
}
});
function validateField(theField) {
msg = "";
//all fields are required
if (theField.type == "text" || theField.type == "password") {
if (theField.value == "") {
msg = "The " + theField.name + " field is required.";
}
}
//name fields are non-numeric
if (theField.name == "fullName"){
if (hasNumber(theField.value) == true){
msg= "The Name field is non-numeric.";
}
}
//email must be correctly formatted
if (theField.name == "email") {
msg = emailCheck (theField.value);
if (msg == "") {
//email address must also be unique
chkEmail();
msg = document.getElementById('emailMessage').innerHTML;
}
}
return msg;
}
function chkEmail() {
emailAddr = document.getElementById("email").value;
$.ajax({
url: '/chkEmail',
type: 'POST',
data: 'emailAddr=' + encodeURIComponent(emailAddr),
dataType: "xml",
context: document.body,
success: function(data) {
document.getElementById('emailMessage').innerHTML = $(data).find("message").text();
}
});
}
<form name="registerNewUserForm" id="registerNewUserForm" action="/register" method="post">
<br/>
<div>Create an Account and join the fun!</div>
<div><input class="validate" type="text" id="fullName" required placeholder="Full Name" name="fullName" value="" size="30"></div>
<div id="fullNameMessage" class="error"></div>
<div><input class="validate" type="text" id="email" required placeholder="Email Address" name="email" value="" size="30"></div>
<div id="emailMessage" class="error"></div>
<div><input class="validate" type="password" id="passWord" required placeholder="Password" name="passWord" value="" size="30"></div>
<div id="passWordMessage" class="error"></div>
<div style="position:relative;left:173px;"><input id="submitButton" type="submit" value="Signup for PastelPlanet"></div>
<input type="hidden" name="formName" value="registerNewUserForm">
<input type="hidden" name="urlDestination" value="">
</form>
Your "chkEmail" function involves a call to the server, and it's asynchronous. The call to the server will not be complete when the function returns, when you're running at "full speed".

Categories

Resources