HTML Form validation using Javascript / PHP - javascript

I have set up a basic contact form which emails the form data via PHP. This works fine but I am having trouble intregrating validation script into the code to prevent the form from submitting when no data is entered.
My code so far is:
PHP to Email the data:
<?php
//validate
if(isset($_POST['submit']))
{
$to="email#testemail.com";
$name=$_REQUEST['name'];
$email=$_REQUEST['email'];
$subject="Contact Us";
$body="Name: $name \n\n Email Address: $email \n\n";
$sent=mail($to, $subject, $body);
echo 'Sent'; die;
}
//
?>
JS to post the form:
$(document).ready(function() {
$("#form1").validate({
submitHandler: function() {
//submit the form
$.post("<?php echo $_SERVER[PHP_SELF]; ?>", //post
$("#form1").serialize(),
function(data){
//if message is sent
if (data == 'Sent') {
$("#message").fadeIn(); //show confirmation message
}
//
});
return false; //don't let the page refresh on submit.
}
}); //validate the form
});
HTML Form
<div id="contact-form">
<form action="" method="post" enctype="multipart/form-data" name="form1" id="form1">
<input type="text" id="name" name="name"/>
<input type="text" id="email" name="email"/>
<input name="submit" type="submit" title="Submit" class="submit_go" value="Submit"/>
</form>
<div id="message">Thank you for your message</div>
</div>
I have tried integrating the below validation script but this doesn't prevent the form from submitting?
Validation Script
function leftValue(e, t, n) {
$(this).text(t.parent()[0].style.left)
}
$(document).ready(function() {
required = ["name", "email"];
email = $("#email");
errornotice = $("#error");
emptyerror = "Required Field";
emailerror = "Required Field";
$("#form1").submit(function() {
for (i = 0; i < required.length; i++) {
var e = $("#" + required[i]);
if (e.val() == "" || e.val() == emptyerror) {
e.addClass("form-error");
e.val(emptyerror);
errornotice.fadeIn(750)
} else {
e.removeClass("form-error")
}
}
if (!/^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA- Z0-9]{2,4})+$/.test(email.val())) {
email.addClass("form-error");
email.val(emailerror)
}
if ($(":input").hasClass("form-error")) {
return false
} else {
errornotice.hide();
return true
}
});
$(":input").focus(function() {
if ($(this).hasClass("form-error")) {
$(this).val("");
$(this).removeClass("form-error")
}
})
});

Aside of your validation in the client you really have to do the validation on the server side all over (in PHP). There is NO guarantee whatsoever that the client side validation happens (users might even have disabled javascript completely), nor that the input comes from your page at all.
Client side validation: eye-candy for the user
Server side validation: where the real security and protection happens.
FWIW: html5 allows for client side validation by the browser.
<form [...]>
<input type="text" id="name" name="name" required="required" placeholder="Name" minlength="2" />
<input type="email" id="email" name="email" required="required" placeholder="Email" />
<input name="submit" type="submit" title="Submit" class="submit_go" value="Submit" />
</form>
More info:
https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Forms/Data_form_validation
https://html.spec.whatwg.org/multipage/forms.html

It might just be as simple as $(":input").hasClass("form-error") > $("input").hasClass("form-error"). I don't see anything else that would prevent this from working.
Although I'd suggest another route. Instead of adding the class form-error to the inputs, then looking for inputs with that class at the end to determine if there was an error, why not just set a boolean flag saying there was an error. That way, there's no additional DOM lookup, which is an expensive operation.
$("#form1").submit(function() {
var isValid = true;
for (i = 0; i < required.length; i++) {
var e = $("#" + required[i]);
if (e.val() == "" || e.val() == emptyerror) {
e.addClass("form-error");
e.val(emptyerror);
errornotice.fadeIn(750);
isValid = false;
} else {
e.removeClass("form-error")
}
}
if (!/^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA- Z0-9]{2,4})+$/.test(email.val())) {
email.addClass("form-error");
email.val(emailerror);
}
if (!isValid) {
return false;
} else {
errornotice.hide();
return true;
}
});

Related

How to disable form submit button if the username already exits in database ? (by js, ajax, php(laravel))

I am new js learner, and I am trying to build a form. in the form I want to check if the input username is already taken or exists and I have done this by laravel controller and lil JS code but I want to HIDE the submit button if the input username is already exists in the database. so how do I do this? please anybody
This is my JS code
<script type="">
$function get_user_name(id, result) {
var id = $(id).val();
$.get("<?php echo e(url('home/get_user_name')) ?>/" + id,
function (data) {
$(result).html(data);
});
}
</script>
Controller =>
**and
controller =**
public function get_user_name()
{
$username = request()->segment(3);
$user = DB::table('users')
->select('username')
->where('username', $username)
->count();
$nam = "username already taken";
if ($user >0) {
return $nam;
}else{
}
}
html form =>
<span id="username_rs" style="color: green; font-weight: bold"></span>//showing the message here,
<input id="username" name="username"
onchange="checkem('#username', '#username_rs')" >
<button type="submit" class="btn btn-primary">
{{ __('Register') }}
</button>
route =>
Route::get('/home/get_user_name/{username}', 'HomeController#get_user_name')->name('checkun');
And url look like =>
http://localhost/home/get_user_name/{input username}
My code is showing if the username is taken or not, but I want to hide the submit button if the username is taken or exists in the database.
You can return like this:
**and
controller =**
public function get_user_name()
{
$username = request()->segment(3);
$user = DB::table('users')
->select('username')
->where('username', $username)
->count();
if ($user >0) {
return Response::json(array("found"=>"yes", "message"=>"Username is already taken"));
}else{
return Response::json(array("found"=>"no", "message"=>"Something happens wrong"));
}
}
Your Script code looks like:
$function get_user_name(id, result) {
var id = $(id).val();
$.get("<?php echo e(url('home/get_user_name')) ?>/" + id,
function (data) {
if (data.found == 'yes)
{
$("#submit_btn").css("display","none")
}
});
}
HTML code looks like:
<span id="username_rs" style="color: green; font-weight: bold"></span>//showing the message here,
<input id="username" name="username"
onchange="checkem('#username', '#username_rs')" >
<button type="submit" id="submit_btn" class="btn btn-primary">
{{ __('Register') }}
</button>
I would do it like this:
function get_user_name(id, result) {
var id = $(id).val();
$.get("<?php echo e(url('home/get_user_name')) ?>/" + id,
function (data) {
//check if we get the message: username already taken
if(data) {
$(result).html(data);
$('input[type=submit]', this).attr('disabled', 'disabled'); //disable button
$('form').bind('submit',function(e){e.preventDefault();}); //disable form
} else {
$('input[type=submit]', this).removeAttr('disabled', 'disabled'); //enable button
$('form').unbind('submit'); //enable form
}
});
}

I'm having a cannot POST when attempting to submit a form with JS

I am having an issue with my Javascript and HTML where when I submit my form, I get a Cannot POST error. I already looked at Shows error "Cannot POST" when I try to submit the HTML form, but that seems to be server-based. I'm sorry, but I'm doing this for a class, so I'm in a bit of a time crunch right now.
My login JS code:
function login(){
var pw = document.forms['login']['passcode'].value;
var email = document.forms['login']["email"].value;
var login = userLogin().get();
if(email == "adrian#tissue.com" && pw == "welcome1"){
window.location = "issues.html";
}
else if(email == "admin#tissue.com" && pw == "admin123"){
window.location = "subscription-dashboard.html"
}
else if(email == login[0] && pw == login[1]){
window.location = "issues.html";
}
else{
alert("That password/email is incorrect");
return false;
};
}
My module for get is:
(function userLogin(){
return {
store: function(password, email){
sessionStorage.setItem(pass, password);
sessionStorage.setItem(user, email);
return false;
},
get: function(){
var mail = sessionStorage.getItem(user);
var pwkey = sessionStorage.getItem(pass);
var loginfo = [mail, pwkey];
return loginfo;
}
}
});
And my HTML code is:
<form action="#" name="login" method="post" onsubmit="return login()">
<input type="text" name="email" placeholder="Email" required>
<input type="password" name="passcode" placeholder = "Password" required>
<input type="submit" value="login">
</form>
Here's my fiddle for ease. I'm using Brackets and this class is Client side JS.
https://jsfiddle.net/MiguelPi/nmp6oxat/1/
Seems like you are trying to access to an anonymous function, rewrite userFunction like this (without external parentheses):
function userLogin(){
return {
store: function(password, email){
sessionStorage.setItem(pass, password);
sessionStorage.setItem(user, email);
return false;
},
get: function(){
var mail = sessionStorage.getItem(user);
var pwkey = sessionStorage.getItem(pass);
var loginfo = [mail, pwkey];
return loginfo;
}
}
}

Javascript check form onsubmit

I've used event.preventDefault() to stop the form action and call the login() , but when the login function return true, it still can't do the form action?
HTML:
<form onsubmit="event.preventDefault();return login();" action="index.php" method="get" id="register-form" >
Javascript:
<script type="text/javascript">
function login() {
var password = window.prompt("Please input password", "");
if (password !== '123') {
alert('Password is incorrect');
return false;
} else {
alert('Success');
return true;
}
}
</script>
Remove event.preventDefault(); from the onsubmit. This will stop the form submission regardless of the value returned from login().
Demo
function login() {
var password = window.prompt("Please input password", "");
if (password !== '123') {
alert('Password is incorrect');
return false;
} else {
alert('Success');
return true;
}
}
<form onsubmit="return login();" action="index.php" method="get" id="register-form">
<input type="submit" value="Login" />
</form>

Javascript to send form to PHP

I am trying to get my HTML form to pass through Javascript that will then pass it to PHP that will send it to MySQL.
However I either get the page to load the JS file in the browser, or the PHP file to load in the browser.
Here is my HTML form:
<div class="form" id="form" onclick="submitForm()">
<form id='contactform' action="js/contactform.js" method="post" onSubmit="submitForm()">
<input type="text" id="name" placeholder="Name" autofocus required><br>
<input type="text" id="email" placeholder="Email" required><br>
<input type="tel" id="telephone" placeholder="Telephone"><br>
Enquiry : <input type="radio" id="subject" value="enquiry" required>
Booking : <input type="radio" id="subject" value="booking" required><br>
<textarea id="message" required rows="20" cols="20" placeholder="Enter your message and I will try to get back to you within 2 days."></textarea><br>
<input type="submit" name="submit" value="Submit" class="submitbutton"/>
<input type="reset" name="clearbutton" value="Clear" class="clearbutton"/>
</form>
<div id="outcome"></div>
I want the outcome of the form submit placed into the "outcome" div
My JS code:
function getOutput() {
getRequest(
'php/getinfo.php',
drawOutput,
drawError
);
return false;
}
// handles drawing an error message
function drawError () {
var container = document.getElementById("content");
container.innerHTML = 'Bummer: there was an error!';
}
// handles the response, adds the html
function drawOutput(responseText) {
var container = document.getElementById("content");
container.innerHTML = responseText;
}
// helper function for cross-browser request object
function getRequest(url, success, error) {
var req = false;
try{
// most browsers
req = new XMLHttpRequest();
} catch (e){
// IE
try{
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
// try an older version
try{
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
return false;
}
}
}
if (!req) return false;
if (typeof success != 'function') success = function () {};
if (typeof error!= 'function') error = function () {};
req.onreadystatechange = function(){
if(req .readyState == 4){
return req.status === 200 ?
success(req.responseText) : error(req.status)
;
}
}
req.open("GET", url, true);
req.send(null);
return req;
}
function submitForm(){
var name = document.getElementById('name').value;
var booking = document.getElementById('subject').value;
var enquiry = document.getElementById('subject').value;
var email = document.getElementById('email').value;
var telephone = document.getElementById('telephone').value;
var message = document.getElementById('message').value;
getRequest(
'php/form.php?' + params, //URL for the PHP file
procesOutput,
processError
);
return false;
}
function processOutput(){
var container = document.getElementById('outcome');
container.innerHTML = responseText;
}
function processError(){
alert("There has been an error, please try again");
}
and my PHP code:
$con=mysqli_connect("DBLocation","Username","Password",'DBName');
if (mysqli_connect_errno()){
die("Error: " . mysqli_connect_error());
}
$result = mysqli_query($con,"INSERT INTO `Contact`(`Name`, `Email`, `Telephone`, `Enquiry`, `Booking`, `Message`) VALUES ([value-2],[value-3],[value-4],[value-5],[value-6],[value-7])");
if ($conn->query($sql) === TRUE){
echo "Thank you for contacting us, I will replay to you soon!";
}
else {
echo "I'm sorry but an Error has occured. Please try again shortly";
}
mysql_close($conn);
?>
I've had a look at w3schools pages and some other questions on here but I can't seem to get my head around it.
A couple of things, first off what is getRequest? Second off, where is responseText defined? Third, I would check your console as I'm pretty sure there is an error in submitForm. I see lots of getElementByIds, but none of your inputs have ids associated with them:
<input type="text" name="name" placeholder="Name" autofocus required>
Should be:
<input type="text" id="name" placeholder="Name" autofocus required>
I believe you want to use Ajax, which you can easily use with jQuery.
I believe the answer for your question is right on this page: https://learn.jquery.com/ajax/ajax-and-forms/
If jQuery is new for you, you might want to read a little about jQuery: https://learn.jquery.com/about-jquery/
If you don't want to use jQuery, you can use directly XMLHttpRequest in javascript instead.
Here is a demo in JSFiddle.
Remove onClick, onSubmit, action="js/contactform.js" method="post" attributes as you don't need them. Capture the form submit in js. How to? - link
Add id's on the form elements so than you can select them like:
var name = document.getElementById('name').value;
Make a $.post request with jQuery (How to? - Link) and handle the success and failure callbacks. (I don't understand why are you making a post request, I would recommend you a $.get request.

when i click on submit button my email is not send why?

when i click on submit button it will show me the message from the javascript file but it will not go to the php file that i have generated..
here is my html code
<form method="post" id="contactForm" action="email_send.php">
<div class="clearfix">
<div class="grid_6 alpha fll">
<input type="text" name="senderName" id="senderName" placeholder="Name *" class="requiredField" />
</div>
<div class="grid_6 omega flr">
<input type="text" name="senderEmail" id="senderEmail" placeholder="Email Address *" class="requiredField email" />
</div>
</div>
<div>
<textarea name="message" id="message" placeholder="Message *" class="requiredField"></textarea>
</div>
<input type="submit" id="sendMessage" name="sendMessage" value="Send Email" />
<span> </span>
</form><!-- end form -->
my js file
if ($("#contactForm")[0]) {
$('#contactForm').submit(function () {
$('#contactForm .error').remove();
$('#contactForm .requiredField').removeClass('fielderror');
$('#contactForm .requiredField').addClass('fieldtrue');
$('#contactForm span strong').remove();
var hasError = false;
$('#contactForm .requiredField').each(function () {
if (jQuery.trim($(this).val()) === '') {
var labelText = $(this).prev('label').text();
$(this).addClass('fielderror');
$('#contactForm span').html('<strong>*Please fill out all fields.</strong>');
hasError = true;
} else if ($(this).hasClass('email')) {
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if (!emailReg.test(jQuery.trim($(this).val()))) {
var labelText = $(this).prev('label').text();
$(this).addClass('fielderror');
$('#contactForm span').html('<strong>Is incorrect your email address</strong>');
hasError = true;
}
}
});
if (!hasError) {
$('#contactForm').slideDown('normal', function () {
$("#contactForm #sendMessage").addClass('load-color');
$("#contactForm #sendMessage").attr("disabled", "disabled").addClass("btn-success").val('Sending message. Please wait...');
});
var formInput = $(this).serialize();
$.post($(this).attr('action'), formInput, function (data) {
$('#contactForm').slideUp("normal", function () {
$(this).before('<div class="notification-box notification-box-success"><p><i class="fa fa-check"></i>Thanks!</strong> Your email was successfully sent. We check Our email all the time.</p></div>');
});
});
}
return false;
});
}
my php file which i have written on action is
<?php
if(isset($_POST['senderName']) && isset($_POST['senderEmail']) && isset($_POST['message']) )
{
$senderName = $_POST['senderName'];
$senderEmail = $_POST['senderEmail'];
$message = $_POST['message'];
if(!empty($senderName) && !empty($senderEmail) && !empty($message))
{
if(strlen($senderName)>25 || strlen($senderEmail)>25 || strlen($message)>50 )
{
echo 'Maximum length reached for each field';
}
else
{
$to = 'info#courtpiece.com';
$subject = 'Court Piece Rung';
$body = "Name:".$senderName."\n"."Message: ".$message;
$header = 'From'.$senderEmail;
if(#mail($to,$subject,$body,$header))
{
echo 'Thanks for Contacting Us.We\'ll in touch soon. ';
}
else
{
echo 'Sorry an error occured ';
}
}
}
else
{
echo 'All fields are required. ';
}
}
?>
Sometimes this can create a problem..
You are using: if(isset($_POST['senderName']) && isset($_POST['senderEmail']) && isset($_POST['message']) ){
instead of:
if(isset($_POST['sendMessage'])){
if(!empty($_POST['senderName']) && !empty($_POST['senderEmail'])){
CODE HERE
}
}
If not, then probably you miss-confiugred your email sending service.
try a test on the email sending.
mail()
You will need to supress the default behaviour of your form so it doesnt also send a request to your server. You do this by calling the prevendDefault function of your event parameter .submit(function(e)....
if ($("#contactForm")[0]) {
$('#contactForm').submit(function (e) {
e.preventDefault(); //to suppress the behaviour of your Form -> you will send data manually with $.post
$('#contactForm .error').remove();
$('#contactForm .requiredField').removeClass('fielderror');
$('#contactForm .requiredField').addClass('fieldtrue');
$('#contactForm span strong').remove();
var hasError = false;
$('#contactForm .requiredField').each(function () {
if (jQuery.trim($(this).val()) === '') {
var labelText = $(this).prev('label').text();
$(this).addClass('fielderror');
$('#contactForm span').html('<strong>*Please fill out all fields.</strong>');
hasError = true;
} else if ($(this).hasClass('email')) {
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if (!emailReg.test(jQuery.trim($(this).val()))) {
var labelText = $(this).prev('label').text();
$(this).addClass('fielderror');
$('#contactForm span').html('<strong>Is incorrect your email address</strong>');
hasError = true;
}
}
});
if (!hasError) {
$('#contactForm').slideDown('normal', function () {
$("#contactForm #sendMessage").addClass('load-color');
$("#contactForm #sendMessage").attr("disabled", "disabled").addClass("btn-success").val('Sending message. Please wait...');
});
var formInput = $(this).serialize();
$.post("email_send.php", formInput, function (data) {
$('#contactForm').slideUp("normal", function () {
$(this).before('<div class="notification-box notification-box-success"><p><i class="fa fa-check"></i>Thanks!</strong> Your email was successfully sent. We check Our email all the time.</p></div>');
});
});
}
return false;
});
}
I have to say that there is room for improvement in the way you have built up this validation.
Try running the form again with the additions I made.
Report back!

Categories