Form validation before AJAX request to submit a form - javascript

I want to validate a form before it submitted with ajax. I wrote the code below but I get a message: "Uncaught ReferenceError: form is not defined" in chrome JS console. The message refer to line 25, where the form.validate function is defined. Any suggestion how to fix it?
Here is the form header:
<form id="contactForm" name="contactForm">
Thanks.
$(document).ready(function(){
var form = document.querySelector("#contactForm");
$("#submitButton").click(function() {
if(form_validate()) {
$.ajax({
type:'GET',
url: 'contact.php',
data: $('#contactForm').serialize(),
success: function(data) {
$("#result").html(data);
}
});
}
return false;
});
});
/*
* #return {boolean}
*/
form_validate = function () {
var name = document.forms["contactForm"]["user-name"].value;
var email = document.forms["contactForm"]["email"].value;
var phone = document.forms["contactForm"]["phone"].value;
var message = document.forms["contactForm"]["message"].value;
var validationAlert = document.getElementById("formValidationAlerts");
var letterOnlyRegExp = /^[a-zA-Z\s]*$/;
var emailRegExp = /^(([^<>()[\]\\.,;:\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,}))$/;
// Check if the fields full name, E-mail and message are filled.
if ((name == null || name == "") ||
(email == null || email == "") ||
(message == null || message == "")) {
validationAlert.innerHTML = "* Your Full Name, Your E-mail Address and Your Message are Required fields." +
" Please fill all of them.";
return false;
}
// Check if the full name is valid (English letters only).
if (!(name.match(letterOnlyRegExp))) {
validationAlert.innerHTML = "* Please Enter a Valid Name (English letters only).";
return false;
}
// Check if the E-mail is valid.
if (!(email.match(emailRegExp))) {
validationAlert.innerHTML = "* Please Enter a Valid E-mail.";
return false;
}
return true;
};
EDIT: I uploaded the updated code. Now the validation works fine, but I got this errors after form submitted (the errors come from the PHP file).
Notice: Undefined index: user-name in /home/web/public_html/contact.php on line 7
Notice: Undefined index: email in /home/web/public_html/contact.php on line 8
Notice: Undefined index: phone in /home/web/public_html/contact.php on line 9
Notice: Undefined index: company in /home/web/public_html/contact.php on line 10
Notice: Undefined index: message in /home/web/public_html/contact.php on line 11
here is the PHP file:
<?php
error_reporting(E_ALL);
ini_set("display_errors", "On");
$subject="Message from Web";
$sender=$_POST["user-name"];
$senderEmail=$_POST["email"];
$senderPhone=$_POST["phone"];
$senderCompany=$_POST["company"];
$message=$_POST["message"];
$mailBody="Name: $sender\nEmail: $senderEmail\nPhone: $senderPhone\nCompany: $senderCompany\n\n$message";
mail('mymail#gmail.com', $mailBody, $sender);
echo "Thank you! we will contact you soon.";
?>

Just try to rename form.validate to form_validate and this should fix your error. Also you should consider to remove method="post" from form headers since you are sending it through AJAX (using GET also!!)

It would appear that the local form variable in this line:
var form = document.querySelector("#contactForm");
is overriding your global form object for which the form.validate method is stored in.
Try changing this line:
if(form.validate()) {
to:
if(window.form.validate()) {

Related

JQuery not displaying HTML data from ajax response

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');
}

Javascript function "does not exist". Bad syntax but can't see it

The javascript is supposed to handle form submission. However, even if called with
script src="js/registerform.js"> Uncaught ReferenceError: sendreg is not defined .
The function is called onclick. Can be reproduced on www.r4ge.ro while trying to register as well as live edited. Tried jshint.com but no clue.
I will edit with any snips required.
function sendreg() {
var nameie = $("#fname").val();
var passwordie = $("#fpass").val();
var emailie = $("#fmail").val();
if (nameie == '' || passwordie == '' || emailie == '') {
alert("Please fill all the forms before submitting!");
} else {
// Returns successful data submission message when the entered information is stored in database.
$.post("http://r4ge.ro/php/register.php", {
numeleluii: nameie,
pass: passwordie,
mail: emailie
}, function(data) {
alert(data);
$('#form')[0].reset(); // To reset form fields
setTimeout(fillhome, 1000);
});
}
}
function sendpass() {
var oldpassw = $("#oldpass").val();
var newpassw = $("#newpass").val();
if (oldpassw == '' || newpassw == '') {
alert("Please fill all the forms before submitting!");
} else {
// Returns successful data submission message when the entered information is stored in database.
$.post("http://r4ge.ro/php/security.php", {
xoldpass: oldpassw,
xnewpass: newpassw
}, function(data2) {
alert(data2);
$('#passform')[0].reset(); // To reset form fields
});
}
}
function sendmail()
{
var curpass = $("#curpass").val();
var newmail = $("#newmail").val();
if (curpass == '' || newmail == '')
{
alert("Please fill all the forms before submitting!");
}
else
{
// Returns successful data submission message when the entered information is stored in database.
$.post("http://r4ge.ro/php/security.php", {
curpass: curpass,
newmail: newmail
}, function(data3) {
alert(data3);
$('#mailform')[0].reset(); // To reset form fields
});
}
}
I'm guessing here but... I imagine you are doing something like
...<button onclick="sendreg">...
And you have your <script> in the bottom on the code. Just put them on top or use $("#mybtn").click(sendreg)
Try using $("#mybtn").click(sendreg) instead of inline onclick.
The script wasn't called in the html. sorry for wasting time. A simple
<script src="js/registerform.js"></script> Fixed it.
There is no syntax error there, and I don't see any such error when trying the page.
The error that you get is that you can't make a cross domain call. Do the request to the same domain:
$.post("http://www.r4ge.ro/php/register.php", {
or:
$.post("/php/register.php", {

How can I use the results of various ajax requests in another function?

I have been programming a registration form with ajax validation. The way I have it set up is in my js file, I have listeners that fire when the content of the field is changed. They send the data to the server, and the server makes sure it's valid and sends back its response in the form of a JSON object. I then read the values of the JSON object to output potential error messages.
I won't copy and paste the entire files, just one example:
$(document).ready(function() {
// USERNAME VALIDATION LISTENER
$("#regUsername").change(checkName);
}
and then the checkName function looks like this, it sends my ajax request:
function checkName() {
$.ajax({
type: "POST",
url: "./ajax_register.php",
data: {
request: "nameAvail",
username: $("#regUsername").val()
},
success: function(data) { // execute on success
var json = jQuery.parseJSON(data);
if (json.success) { // if usernames do match
$("#usernameAvailiability").removeClass().addClass('match');
$("#usernameAvailiability").text(json.msg);
} else { // if the user has failed to match names
$("#usernameAvailiability").removeClass().addClass('nomatch');
$("#usernameAvailiability").text(json.msg);
}
}
});
}
And depending on the response, it updates a span that tells the user if the input they wrote is valid or not.
The server validates with this part of the php file:
if(!isset($_POST['request'])) { // do nothing if no request was provided
print("no request provided");
} else { //ELSE request has been provided
if ($_POST['request'] == "nameAvail") { // if the request is to check if the username is valid
$response = array("success" => false, "msg" => " ", "request" => "nameAvail");
// CHECK USER NAME AVAILIABILITY CODE
if (!isset($_POST['username']) || empty($_POST['username'])) { // if no username is entered
$response['success'] = false;
$response['msg'] = "No username provided";
} else { // if a username has been entered
$username = $dbConn->real_escape_string($_POST['username']);
if (!ctype_alnum($username)) { // Make sure it's alpha/numeric
$response['success'] = false;
$response['msg'] = "username may only contain alpha numeric characters";
} elseif (strlen($username) < 4) { // make sure it's greater than 3 characters
$response['success'] = false;
$response['msg'] = "username must be at least 4 characters long.";
} elseif (strlen($username) > 20) { // make sure it's less than 26 characters
$response['success'] = false;
$response['msg'] = "username can be up to 20 characters long.";
} else { // make sure it's not already in use
$query = $dbConn->query("SELECT `id`, `username` FROM `users` WHERE `username` = '"
. $username . "' LIMIT 1");
if ($query->num_rows) { // if the query returned a row, the username is taken
$response['success'] = false;
$response['msg'] = "That username is already taken.";
} else { // No one has that username!
$response['success'] = true;
$response['msg'] = "That username is availiable!";
}
}
}
print(json_encode($response));
}
What I'd like to do now is create a function in my javascript for the register button. But I need to make sure all the forms are validated first.
I'm not sure what my options are. What I'd LIKE to do is somehow be able to recycle the code I've already written in my PHP file. I don't want to write out an entirely new if($_POST['request'] == "register") clause and then copy and paste all the validation code to make sure the input is valid before I insert the registrant's data into the database. It seems really repetitive!
I know I could check to see if all the spans on the page were set to 'match', but that could easily be tampered with and blank forms could be submitted.
so far, my register button function looks like this:
function register() {
if ( NEED SOME KIND OF CLAUSE HERE TO CHECK IF ALL THE FIELDS ARE VALID) {
$.ajax({
type: "POST",
url: "./ajax_register.php",
data: {
request: "register",
username: $("#regUsername").val(),
password: $("#regPassword").val(),
email: $("#email").val(),
dob: $("#dob").val(),
sQuest: $("#securityQuestion").val(),
sAns: $("#securityAnswer").val(),
ref: $("#referred").val()
}, success: function(data) {
var json = jQuery.parseJSON(data);
console.log(json);
$("#regValid").removeClass();
$("#regValid").text("");
}
}); //AJAX req done
} else {
$("#regValid").removeClass().addClass('nomatch');
$("#regValid").text("One or more fields are not entered correctly");
}
return false;// so that it wont submit form / refresh page
}
I would really appreciate some help, I've spent the last few hours scouring StackOverflow for an answer, but I can't seem to get anything to work. Will I have to duplicate code in my PHP file or is there a more elegant way to handle this?

Basic Form Validation with JavaScript/HTML

I'm writing a form validation script for my Contact Us form I made. The script is pretty straight forward, I am wondering why it isn't working correctly.
No matter what fields I have content in, it always says that field is empty after running the script.
Here is my code:
var firstName = document.getElementById("fname");
var lastName = document.getElementById("lname");
var email = document.getElementById("email");
var message = document.getElementById("msg");
var errors = "";
function formValidation() {
if (firstName==="" || firstName=== null)
{
errors += "-The First Name field is blank! \n";
}
if (lastName==="" || lastName=== null)
{
errors += "-The Last Name field is blank! \n";
}
if (email==="" || email=== null)
{
errors += "-The E-mail Address field is blank! \n";
}
if (message==="" || message=== null)
{
errors += "-The Message field is blank! \n";
}
if (errors !== "") {
alert("Whoops! \n \n" + errors);
}
if (errors === "") {
alert("Message Sent!");
}
}
Additionally, here is the jsfiddle I made: http://jsfiddle.net/3DxZj/1/
Thank you.
First, you are trying to get the elements by their ids before they exist in the DOM (the script is above the form).
Second, if you corrected that then you would be comparing the HTMLInputElements themselves to an empty string, instead of their .value properties.
Third, you never reset errors so if anybody did get an error and them fixed it, they would still get the error alert when they tried again.
Add .value to the elements you are trying to get and move the following code so it is inside the function.
var firstName = document.getElementById("fname").value;
var lastName = document.getElementById("lname").value;
var email = document.getElementById("email").value;
var message = document.getElementById("msg").value;
var errors = "";
You are also only checking for errors when the form is submitted using the submit button. You should do this when the form is submitted instead.
Move the onclick attribute contents to an onsubmit attribute on the form element. Better yet, bind your event listener with JS.
You aren't preventing the normal action of the form when there are errors. Presumably you want it to stop the data from submitting. Either:
Use addEventListener (see above), accept an argument for your function and call .preventDefault() on that argument's value when there are errors or
Add return to the front of your onsubmit attribute value and return false from the function when there are errors.
Also note that
Your label elements are useless; they need for attributes.
You shouldn't use tables to layout (most) forms.
The values will always be strings so there is no point in comparing to null.
You are querying the dom elements but not their values. The correct way would be
var firstName = document.getElementById("fname");
var lastName = document.getElementById("lname");
var email = document.getElementById("email");
var message = document.getElementById("msg");
var errors = "";
function formValidation() {
if (firstName.value==="" || firstName.value=== null)
{
errors += "-The First Name field is blank! \n";
}
if (lastName.value==="" || lastName.value=== null)
{
errors += "-The Last Name field is blank! \n";
}
if (email.value==="" || email.value=== null)
{
errors += "-The E-mail Address field is blank! \n";
}
if (message.value==="" || message.value=== null)
{
errors += "-The Message field is blank! \n";
}
if (errors !== "") {
alert("Whoops! \n \n" + errors);
}
if (errors === "") {
alert("Message Sent!");
}
}
EDIT: Stupid me, didn't check the jsfiddle so I solved only one of your problems while making a mistake in my solution (corrected now), so stick to Quentins answer
The issue is that you are not returning the .value of the form fields.
eg: var firstName = document.getElementById("fname").value;
Also, you should declare your vars inside the function.
Try this:
function formValidation() {
var firstName = document.getElementById("fname").value;
var lastName = document.getElementById("lname").value;
var email = document.getElementById("email").value;
var message = document.getElementById("msg").value;
var errors = "";
if (firstName==="" || firstName=== null)
{
errors += "-The First Name field is blank! \n";
}
if (lastName==="" || lastName=== null)
{
errors += "-The Last Name field is blank! \n";
}
if (email==="" || email=== null)
{
errors += "-The E-mail Address field is blank! \n";
}
if (message==="" || message=== null)
{
errors += "-The Message field is blank! \n";
}
if (errors !== "") {
alert("Whoops! \n \n" + errors);
}
if (errors === "") {
alert("Message Sent!");
}
}

javascript onBlur not working, and how to connect javascript files

I have two javascript files that I am using to validate an email address.
validate.js:
function checkEmail(userEmail) {
var email = userEmail
var emailFilter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (emailFilter.test(email.value)) {
//alert('Please provide a valid email address');
//email.focus;
return true;
}
else{
return false
}
}
navigation.js EDIT:
$(document).ready(function() {
//ADDED IMPORTS
var imported = document.createElement('script');
imported.src = 'lib/validation.js';
document.head.appendChild(imported);
console.log("DOCUMENT IS READY!");
var viewsWrapper = $("#views-wrapper");
var loginButton = $("#login-button");
var registerButton = $("#register-button");
// Login Link
// TODO: Unclear if needed
$("ul li.login").click(function() {
$.get('/login', function(data) {
viewsWrapper.html(data);
});
});
$('#usernamefield').blur(function() {
var sEmail = $('#usernamefield').val();
if ($.trim(sEmail).length == 0) {
alert('Please enter valid email address');
e.preventDefault();
}
if (checkEmail(sEmail)) {
alert('Email is valid');
}
else {
alert('Invalid Email Address');
e.preventDefault();
}
});
...(more code follows but not relevant)
I am also using this jade template:
login.jade:
form(action="")
key EMAIL
input(type="text", name="username", id="usernamefield")
p hello world
br
key PASSWORD
input(type="text", name="password", id="passwordfield")
p hello world
br
input(type="submit", name="loginButton", id="login-button", value="LOGIN")
My issue is that when I input something into my email field, I do not get an alert message in any case. Am I allowed to just have to separate javascript files and call the methods I defined in validate.js within navigation.js? I tried putting the validate.js code in navigation.js, but even then it did not work. I would like to keep the files separate. Am I missing something obvious? I want it so that once the user inputs the email, and leaves the field, a message should appear warning if the email is valid or not.
Your help is appreciated.
Is it the blur Event or the checkEmail the problem? try to put a alert() or console.log() just after your blur (and make sure to lose focus on your input). Seperate file shouldn't be a problem. And also have you check for errors in your console ?
JavaScript string has no "value" field
After
var sEmail = $('#username').val();
sEmail becomes a string.
You are passing this string to checkEmail method and try to get "value" from a string:
if(!emailFilter.test(email.value)) {//...}
Replace to
if (!emailFilter.test(email)) {//...}
You are already sending the value of email into checkemail function. So in checkEmail function in validate.js remove email.value in second line of function checkEmail
function checkEmail(userEmail) {
var email = userEmail
var emailFilter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (!emailFilter.test(email)) {
//alert('Please provide a valid email address');
email.focus;
return false;
}
}

Categories

Resources