php form action and jquery validation executing at once - php

My jquery validation and php form are both executing at once, means the validations errors are showing and also the php action is executed. here is the complete code. The jquery form submit function is returning false if the there are errors in form but even thought the form getting executed..
<form class="form-3 form-horizontal ajxfrm " id="step-three" enctype="multipart/form-data" action="<?php echo $html->addLink(array('controller'=>'homes','action'=>'step_three')); ?>" method="post" target="_parent">
<div id="calendar">
<div class="clear"></div>
<div class="control-group">
<div class="control-label">Name<span>*</span></div>
<div class="controls"><input type="text" name="name" id="name" />
<span id="nameInfo"></span></div>
</div>
<div class="control-group">
<div class="control-label">Email<span>*</span></div>
<div class="controls"><input type="text" name="email" id="email" />
<span id="emailInfo"></span></div>
</div>
<div class="control-group">
<div class="control-label">Contact<span>*</span></div>
<div class="controls"><input type="text" name="contact" id="contact" />
<span id="contactInfo"></span></div>
</div>
<div class="control-group">
<div class="control-label">Skype Id<span>*</span></div>
<div class="controls"><input type="text" name="skypeid" id="skype" />
<span id="skypeInfo"></span></div>
</div>
<div style="position:relative">
<div class="control-group">
<div class="control-label">Files<br/><span style="font-size:10px; font-style:italic">(Optional)</span></div>
<div class="controls">
<input id="fileupload" type="file" name="fileupload[]" multiple/>
<span id="fileInfo"></span><br/>
</div>
</div>
</div>
<div class="control-group">
<div class="control-label">Your Message<span>*</span></div>
<div class="controls"><textarea rows="3" name="message" id="message"></textarea>
<span id="messageInfo"></span></div>
</div>
<div class="clear"></div>
</div>
<div id="submit" style=" text-align:right;">
<input type="hidden" name="post" value="1"/>
<input type="submit" class="btn green" value="Next" id="step3submit" style="margin-right:-20%; margin-top:5%"/>
</div>
</form>
Here is the jquery file
$(document).ready(function () {
//global vars
var form = $("#step-three");
var name = $("#name");
var nameInfo = $("#nameInfo");
var email = $("#email");
var emailInfo = $("#emailInfo");
var contact = $("#contact");
var contactInfo = $("#contactInfo");
var skype = $("#skype");
var skypeInfo = $("#skypeInfo");
var message = $("#message");
//On blur
name.blur(validateName);
email.blur(validateEmail);
contact.blur(validateContact);
skype.blur(validateSkype);
message.blur(validateMessage);
//On key press
name.keyup(validateName);
email.keyup(validateEmail);
contact.keyup(validateContact);
skype.keyup(validateSkype);
message.keyup(validateMessage);
//On Submitting
form.submit(function () {
if (validateName() & validateEmail() & validateContact() & validateSkype() & validateMessage())
return true;
else
return false;
});
//validation functions
function validateEmail() {
//testing regular expression
var a = $("#email").val();
var filter = /^\w+#[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/;
//if it's valid email
if (email.val().length == 0) {
email.addClass("error");
emailInfo.text("Required");
emailInfo.addClass("error");
return false;
} else if (filter.test(a)) {
email.removeClass("error");
emailInfo.text("");
emailInfo.removeClass("error");
return true;
}
//if it's NOT valid
else if (!filter.test(a)) {
email.addClass("error");
emailInfo.text("Valid Email Please");
emailInfo.addClass("error");
return false;
}
}
function validateName() {
//if it's NOT valid
if (name.val().length == 0) {
name.addClass("error");
nameInfo.text("Required");
nameInfo.addClass("error");
return false;
}
//if it's valid
else {
name.removeClass("error");
nameInfo.text("");
nameInfo.removeClass("error");
return true;
}
}
function validateContact() {
//if it's NOT valid
if (contact.val().length == 0) {
contact.addClass("error");
contactInfo.text("Required");
contactInfo.addClass("error");
return false;
}
//if it's valid
else {
contact.removeClass("error");
contactInfo.text("");
contactInfo.removeClass("error");
return true;
}
}
function validateSkype() {
//if it's NOT valid
if (skype.val().length == 0) {
skype.addClass("error");
skypeInfo.text("Required");
skypeInfo.addClass("error");
return false;
}
//if it's valid
else {
skype.removeClass("error");
skypeInfo.text("");
skypeInfo.removeClass("error");
return true;
}
}
/* function validatePass1(){
var a = $("#password1");
var b = $("#password2");
//it's NOT valid
if(pass1.val().length <5){
pass1.addClass("error");
pass1Info.text("Ey! Remember: At least 5 characters: letters, numbers and '_'");
pass1Info.addClass("error");
return false;
}
//it's valid
else{
pass1.removeClass("error");
pass1Info.text("At least 5 characters: letters, numbers and '_'");
pass1Info.removeClass("error");
validatePass2();
return true;
}
}
function validatePass2(){
var a = $("#password1");
var b = $("#password2");
//are NOT valid
if( pass1.val() != pass2.val() ){
pass2.addClass("error");
pass2Info.text("Passwords doesn't match!");
pass2Info.addClass("error");
return false;
}
//are valid
else{
pass2.removeClass("error");
pass2Info.text("Confirm password");
pass2Info.removeClass("error");
return true;
}
}*/
function validateMessage() {
//it's NOT valid
if (message.val().length < 10) {
message.addClass("error");
messageInfo.text("More than 10 Characters required");
messageInfo.addClass("error");
return false;
}
if (message.val().length == 0) {
message.addClass("error");
messageInfo.text("Required");
messageInfo.addClass("error");
return false;
}
//it's valid
else {
message.removeClass("error");
messageInfo.text("");
messageInfo.removeClass("error");
return true;
}
}
});

You have to use preventDefault() function. The submit function can't be 'canceled' with returning false. it is an event and there are many handlers 'listening' to it. You have to stop the event from propagating, thus preventing the handlers to handle the event ;)
The code:
$("form").submit(function(e){
if(!(validateName() && validateEmail() && validateContact() && validateSkype() && validateMessage())){
e.preventDefault();
// and maybe some alert() with fail info
}
else{
//whatever you need if validation suceeds
}
});

use && place of &
I hope it will help

Related

how to validate the minlength and maxlength of textarea?

I want to validate the minlength and maxlength of textarea before submitting, can anyone tell me details?
<form id="contact-je" action="<?php echo JURI::current(); ?>" method="post">
<div class="input">
<label id="je_hide_message" for="message"><?php echo JText::_("$message"); ?></label>
<textarea name="je_message" id="message" class="requiredField" rows="4"
placeholder="<?php echo $message; ?>"><?php if (isset($_POST['je_message'])) {
if (function_exists('stripslashes')) {
echo stripslashes($_POST['je_message']);
} else {
echo $_POST['je_message'];
}
} ?></textarea>
<?php if (!isset($_SESSION)) {
if ($messageError != '') { ?><span
class="error"><?php echo $messageError; ?></span><?php }
} ?>
</div>
<div class="input">
<button name="submit" type="submit"
class="je_button"><?php echo JText::_("$submit") ?></button>
<input type="hidden" name="submitted" id="submitted" value="true"/>
</div>
</form>
<?php } ?>
</div>
If you are allowed to use the browser feature, you can just set minlength and maxlength attributes of <textarea>.
<form>
<textarea minlength="5" maxlength="10"></textarea>
<input type="submit">
</form>
I add following codes, but if enter more than 300characters, the form will still be submitted. I don't want to submit if the characters is over 300
// Validate error
$('form#contact-je').submit(function () {
$('form#contact-je .error').remove();
var hasError = false;
$('.requiredField').each(function () {
if ($.trim($(this).val()) == '') {
var labelText = $(this).prev('label').text();
$(this).parent().append('<span class="error">Pls enter ' + labelText + '!</span>');
$(this).addClass('invalid');
hasError = true;
} else if ($(this).hasClass('email')) {
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if (!emailReg.test($.trim($(this).val()))) {
var labelText = $(this).prev('label').text();
$(this).parent().append('<span class="error">You\'ve entered an invalid ' + labelText + '!</span>');
$(this).addClass('invalid');
hasError = true;
}
}
});
//Limit message characters
$('#message').keyup(function() {
if ($(this).val().length > 300){
$(this).parent().append('<span class="error">ffffff</span>');
$(this).addClass('invalid');
hasError = true;
}
});
if (!hasError) {
var formInput = $(this).serialize();
$.post($(this).attr('action'), formInput, function (data) {
$('form#contact-je').slideUp("fast", function () {
$(this).before('<span class="success"><strong>Thank you!</strong> We have received your email.<br />We will get back to you in 12 hours.<br />-- Pneuflex China</span>');
});
});
}
return false;
});

Pass form field values data to another page with php

I have two PHP pages: index.php and thankyou.php. In index.php, there is a form. I am validating form with Javascript and ajax and the form values are being inserted into database. After database query I am redirecting this form to Thankyou.php. What i want is to pass form field values to thankyou.php. Please find below the complete code. :
Sql query running in header :-
?php
error_reporting(0);
include_once('cc/connect.php');
if($_SERVER['REQUEST_METHOD'] === 'POST')
{
$str="insert into registration(fname,lname,email,mobile_number,code,designation,organization,comps,city,affid,date_time,status)values('".mysql_escape_string($_POST['txtfname'])."','".mysql_escape_string($_POST['txtlname'])."','".mysql_escape_string($_POST['txtemail'])."','".mysql_escape_string($_POST['txtmobilenumber'])."','".mysql_escape_string($_POST['txtcode'])."','".mysql_escape_string($_POST['desig'])."','".mysql_escape_string($_POST['org'])."','".mysql_escape_string($_POST['comps'])."','".mysql_escape_string($_POST['txtcity'])."','".mysql_escape_string($_POST['txtaff'])."',now(),0)";
$rslt=mysql_query($str);
if(!$rslt)
{
echo '<script type="text/javascript">
alert("We are experiencing some issues, please try later");
</script>
';
}
else
{
echo '<script type="text/javascript">
window.location.href="thankyou.php";
</script>
';
}
}
?>
Javascript Validation :-
<script type="text/javascript">
function validate_form()
{
var pattern =/^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
var mob=/^(\+91[\-\s]?)?[89]\d{9}$/;
if(document.getElementById('txtfname').value=="" || document.getElementById('txtfname').value==null)
{
alert("Please enter First Name");
document.getElementById('txtfname').focus();
return false;
}
if(document.getElementById('txtlname').value=="" || document.getElementById('txtlname').value==null)
{
alert("Please enter Last Name");
document.getElementById('txtlname').focus();
return false;
}
if(document.getElementById('txtemail').value=="" || document.getElementById('txtemail').value==null)
{
alert("Please enter the Email");
document.getElementById('txtemail').focus();
return false;
}
if(!pattern.test(document.getElementById('txtemail').value))
{
alert("Please enter the valid Email");
document.getElementById('txtemail').focus();
return false;
}
if(document.getElementById('txtmobilenumber').value=="" || document.getElementById('txtmobilenumber').value==null)
{
alert("Please enter the Mobile Number");
document.getElementById('txtmobilenumber').focus();
return false;
}
if(document.getElementById('txtcode').value=="" || document.getElementById('txtcode').value==null)
{
alert("Please enter verification code");
document.getElementById('txtcode').focus();
return false;
}else
{
check_existence(document.getElementById('txtcode').value,6);
}
if(document.getElementById('comps').value=="" || document.getElementById('comps').value==null)
{
alert("Please enter Company strength");
document.getElementById('comps').focus();
return false;
}
if(!isNaN(document.getElementById('comps').value))
{
alert("Please select the valid Company strength");
document.getElementById('comps').value='';
document.getElementById('comps').focus();
return false;
}
if(document.getElementById('org').value=="" || document.getElementById('org').value==null)
{
alert("Please enter Organization");
document.getElementById('org').focus();
return false;
}
if(document.getElementById('txtcity').value=="" || document.getElementById('txtcity').value==null)
{
alert("Please enter the city");
document.getElementById('txtcity').focus();
return false;
}
if(!isNaN(document.getElementById('txtcity').value))
{
alert("Please enter the valid city");
document.getElementById('txtcity').value='';
document.getElementById('txtcity').focus();
return false;
}
}
function check_existence(val,caseno)
{
var pattern = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
var mob=/^(\+91[\-\s]?)?[789]\d{9}$/;
var xmlhttp;
if(caseno=="1")
{
if(!pattern.test(document.getElementById('txtemail').value))
{
alert("Please enter the valid email");
document.getElementById('txtemail').value='';
document.getElementById('txtemail').focus();
return false;
}
}
if(caseno=="2")
{
if(!mob.test(document.getElementById('txtmobilenumber').value))
{
alert("Please enter the valid mobile number");
document.getElementById('txtmobilenumber').value='';
document.getElementById('txtmobilenumber').focus();
return false;
}
}
if(caseno=="3")
{
if(!mob1.test(document.getElementById('txtname').value))
{
alert("Please enter the valid mobile number");
document.getElementById('txtname').value='';
document.getElementById('txtname').focus();
return false;
}
}
if(window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP")
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
if(xmlhttp.responseText=="1")
{
alert("Email address already exists");
document.getElementById('txtemail').value='';
document.getElementById('txtemail').focus();
}
if(xmlhttp.responseText=="2")
{
alert("Verification code has been sent to your mobile");
document.getElementById('txtcode').focus();
}
if(xmlhttp.responseText=="3")
{
document.forms["formsms"].submit();
}
if(xmlhttp.responseText=="4")
{
alert("Please enter the valid verification code");
document.getElementById('txtcode').focus();
}
if(xmlhttp.responseText=="5")
{
alert("Mobile Number already exists");
document.getElementById('txtmobilenumber').value='';
document.getElementById('txtmobilenumber').focus();
}
}
}
xmlhttp.open("GET","ajax_file.php?caseno="+caseno+"&val="+val,true);
xmlhttp.send();
}
</script>
Form Code :-
<div class="form-content">
<form class="form-box register-form form-validator" id="formsms" name="formsms" method="post">
<div class="form-group">
<label>First name: <span class="required">*</span></label>
<input class="form-control" type="text" name="txtfname" id="txtfname" required>
</div>
<div class="form-group">
<label>Last name: <span class="required">*</span></label>
<input class="form-control" type="text" name="txtlname" id="txtlname" required>
</div>
<div class="form-group">
<label>Email: <span class="required">*</span></label>
<input class="form-control" type="email" name="txtemail" id="txtemail" onchange="return check_existence(this.value,1);" required>
</div>
<div class="form-group">
<div style="float:left; width:270px;" >
<label>Mobile: <span class="required">*</span></label>
<input class="form-control" type="text" name="txtmobilenumber" id="txtmobilenumber" onchange="return check_existence(this.value,2);" required>
</div>
<div style="float:right">
<label>Verification Code: <span class="required">*</span></label>
<input class="form-control" type="text" name="txtcode" id="txtcode" required>
</div>
</div>
<div style="clear:both;"></div>
<div class="form-group">
<label>Select Graduation: <span class="required">*</span></label>
<select class="form-control" name="comps" id="comps">
<option>Select...</option>
<option value="BA">BA</option>
<option value="BBA">BBA</option>
<option value="BCom">BCom</option>
<option value="BSC">BSC</option>
<option value="BTech">BTech</option>
<option value="Other">Other</option>
</select>
</div>
<div class="form-group">
<label>Graduation%: <span class="required">*</span></label>
<input class="form-control" type="text" name="org" id="org" required>
</div>
<div class="form-group">
<label>City: <span class="required">*</span></label>
<input class="form-control" type="text" name="txtcity" id="txtcity" required>
</div>
<div class="buttons-box clearfix">
<input type="button" id="btnsubmit" name="btnsubmit" class="btn btn-default" value="Submit" onclick="return validate_form()"/>
<span class="required"><b>*</b> Required Field</span>
<br>
</div>
</form><!-- .form-box -->
</div>
The simplest way is to use PHP sessions. These will store data from one interaction with the user, to be retrieved on another interaction.
In connect.php, add:
session_start();
In index.php, after you've validated and saved info in the DB, save the data that you want to pass between pages in the $_SESSION array
$_SESSION['fname'] = $_POST['txtfname'];
....
It's actually better to save things to session after you've done all string manipulation (eg: after applying mysql_escape_string).
Now, whenever the user makes another request, you can find the data in that same array. So on thankyou.php
$fname = $_SESSION['fname'];
...
Here is a basic intro to sessions.
This next note goes beyond your question but it's one really important lesson: sessions rely on cookies to recognize a user when he makes another visit. This means that a savvy user can manipulate this cookie and break his session or try to present himself as someone else in order to bypass your security restrictions. Once you're comfortable with the basics, look into how to use sessions securely!
This sounds like a typical case when $_SESSION may come in handy. In this Case (since you are doing your thing with AJAX), you may want to handle the Session in your AJAX Processing PHP File... (header.php?) Well here's how:
<?php
// FILE-NAME: header.php //<== THE AJAX PROCESSING SCRIPT
//FIRST CHECK IF SESSION EXIST BEFORE STARTING IT:
if (session_status() == PHP_SESSION_NONE || session_id() == '') {
session_start();
}
error_reporting(0);
include_once('cc/connect.php');
if($_SERVER['REQUEST_METHOD'] === 'POST') {
// JUST START SETTING UP THE SESSION DATA IF DATA WAS POSTED...
$_SESSION['fname'] = htmlspecialchars(trim($_POST['txtfname']));
$_SESSION['lname'] = htmlspecialchars(trim($_POST['txtlname']));
$_SESSION['email'] = htmlspecialchars(trim($_POST['txtemail']));
$_SESSION['mobile_number'] = htmlspecialchars(trim($_POST['txtmobilenumber']));
$_SESSION['code'] = htmlspecialchars(trim($_POST['txtcode']));
$_SESSION['designation'] = htmlspecialchars(trim($_POST['desig']));
$_SESSION['organization'] = htmlspecialchars(trim($_POST['org']));
$_SESSION['comps'] = htmlspecialchars(trim($_POST['comps']));
$_SESSION['city'] = htmlspecialchars(trim($_POST['txtcity']));
$_SESSION['affid'] = htmlspecialchars(trim($_POST['txtaff']));
$_SESSION['date_time'] = date("Y-m-d", time());
$_SESSION['status'] = "0";
$str="insert into registration(fname,lname,email,mobile_number,code,designation,organization,comps,city,affid,date_time,status)values('".mysql_escape_string($_POST['txtfname'])."','".mysql_escape_string($_POST['txtlname'])."','".mysql_escape_string($_POST['txtemail'])."','".mysql_escape_string($_POST['txtmobilenumber'])."','".mysql_escape_string($_POST['txtcode'])."','".mysql_escape_string($_POST['desig'])."','".mysql_escape_string($_POST['org'])."','".mysql_escape_string($_POST['comps'])."','".mysql_escape_string($_POST['txtcity'])."','".mysql_escape_string($_POST['txtaff'])."',now(),0)";
$rslt=mysql_query($str);
//... THE REST OF YOUR CODE...
}
Then, inside of thankyou.php, you can do this:
<?php
// FILE-NAME: thankyou.php
//FIRST CHECK IF SESSION EXIST BEFORE STARTING IT:
if (session_status() == PHP_SESSION_NONE || session_id() == '') {
session_start();
}
// TO GET THE EMAIL, FIRST & LAST NAMES HERE, YOU CAN SIMPLE DO LIKE SO:
$email = isset( $_SESSION['email'] )? $_SESSION['email'] : "";
$firstName = isset( $_SESSION['fname'] )? $_SESSION['fname'] : "";
$lastName = isset( $_SESSION['lname'] )? $_SESSION['lname'] : "";
// ASSUMING YOU WANT TO THANK THE USER BY NAME:
// YOU MAY DO SOMETHING LIKE SO:
$thankYou = "<div class='thank-you'>" . PHP_EOL;
$thankYou .= "<p class='appreciation'>Thank you, " ;
$thankYou .= "<span class='user-name'>{$firstName} {$lastName}</span>";
$thankYou .= " for your E-Mail... bla...bla..</p>" .PHP_EOL;
$thankYou = "</div>" . PHP_EOL;
echo $thankYou;

stop form from submitting (tried e.preventDefault() after $.post but it stops form from submitting

I have this in javascript
$('#submit').on('click', function(e) {
$('#message_line').text("");
if(validate_fields_on_submit()) {
e.preventDefault();
return;
}
// e.preventDefault();
var params = $('form').serialize();
$.post('check_duplicate.php', params, function(responseText) {
submitHandler(responseText);
});
// e.preventDefault();
//return false;
});
function submitHandler(response) {
$('#message_line').text("");
response = $.trim(response);
if(response == "" && response.indexOf("<") <= -1)
$('#registration').submit();
else if(response.indexOf("<") == 0) {
var name = $('[name="regusername"]').val();
$('#message_line').text("Some error occured, please try after some time.");
$("#message_line").attr("tabindex",-1).focus();
return false;
} else {
var name = $('[name="regusername"]').val();
var arr = response.split(',');
arr.pop();
arr.toString();
$('#message_line').text("'" + name + "' already exists, Please try different username");
$("#regusername").focus();
return false;
}
$('#busy_wait').css('display','none');
}
HTML CODE
<?php
session_start();
if ($_SERVER["REQUEST_METHOD"] == "POST") {
include("db/helper_functions.php");
if(validate_fields()) {
if(!check_duplicate($_POST["regusername"])) {
$count = insert_record($_POST["fname"],$_POST["lname"],$_POST["email"],$_POST["regusername"],$_POST["regpassword"]);
if($count > 0) {
include("includes/confirmation.php");
exit();
}
else {
$error = "Sorry registration failed, please try again.";
}
}
else {
$error = "Username already exists, please try different username.";
}
}
}
$page_title = "Registration";
if(isset($_SESSION["username"]))
include('includes/header_authorized.html');
else
include('includes/header.html');
?>
<div class="container">
<div class="regform">
<form name="registration" id="registration" method="post" action="registration.php">
<p><span class="req">* required field.</span></p>
<ul>
<li><label for="fname">First Name:</label>
<input type="text" class="textboxborder" id="fname" name="fname" size="20" maxlength="25" autofocus="autofocus" value="<?php if(isset($_POST['fname'])) echo $_POST['fname'];?>"/>
<span class="error" id="errfname">*<?php if(isset($errfname)) echo $errfname;?></span>
</li>
<li><label for="lname">Last Name:</label>
<input type="text" class="textboxborder" id="lname" name="lname" size="20" maxlength="25" value="<?php if(isset($_POST['lname'])) echo $_POST['lname'];?>"/>
<span class="error" id ="errlname">*<?php if(isset($errlname)) echo $errlname;?></span>
</li>
<li><label for="email">Email:</label>
<input type="text" class="textboxborder" name="email" id="email" size="40" maxlength="50" placeholder="abc#xyz.com" value="<?php if(isset($_POST['email'])) echo $_POST['email'];?>"/>
<span class="error" id="erremail">*<?php if(isset($erremail)) echo $erremail;?></span>
</li>
<li><label for="regusername">Username:</label>
<input type="text" name="regusername" id="regusername" size="20" maxlength="30" value="<?php if(isset($_POST['regusername'])) echo $_POST['regusername'];?>"/>
<span class="error" id="errregusername">*<?php if(isset($errregusername)) echo $errregusername;?></span>
</li>
<li><label for="regpassword">Password:</label>
<input type="password" name="regpassword" id="regpassword" size="20" maxlength="15" value="<?php if(isset($_POST['regpassword'])) echo $_POST['regpassword'];?>"/>
<span class="error" id="errregpassword">*<?php if(isset($errregpassword)) echo $errregpassword;?></span>
</li>
<li><label for="regconpassword">Confirm Password:</label>
<input type="password" name="regconpassword" id="regconpassword" size="20" maxlength="15"/>
<span class="error" id="errregconpassword">*<?php if(isset($errregconpassword)) echo $errregconpassword;?></span>
</li>
</ul>
<div id="message_line"> <?php if(isset($error)) echo $error;?></div>
<div class="buttons">
<input type="reset" value="Reset" id="reset"/>
<input type="submit" value="Submit" />
</div>
</form>
<img src="images/loading.gif" id="busy_wait" alt="busy wait icon" />
</div>
</div>
</body>
</html>
If in submit handler control goes in else if or else block form submission does not stop,I tried return false; and I tried using e.preventDefault(); at different places before ajax call and after but that stops form submission even after validation success and successful return from check_duplicate.php
Any help would be appreciated.
Assuming you have a submit button with id=submit, I would
rename the button since calling anything submit is poor practice since you need to actually submit the form programatically.
move the handler to the form submit event - I personally NEVER attach a handler to a submit button
I assume you do NOT want to submit if the validation returns false
Like this
$('#registration').on('submit', function(e) {
e.preventDefault();
$('#message_line').text("");
if(!validate_fields_on_submit()) { // I assume you meant NOT
return;
}
var params = $(this).serialize();
$.post('check_duplicate.php', params, function(responseText) {
submitHandler(responseText);
});
});
the post can be written
$.post('check_duplicate.php', params, submitHandler);
UPDATE Here is the complete script - NOTE IMPERATIVE to rename anything name=submit or id=submit to something else
$(function() {
$('#registration').on('submit', function(e) {
e.preventDefault();
$('#message_line').text("");
if(!validate_fields_on_submit()) { // I assume you meant NOT
return;
}
$('#busy_wait').show();
$.post('check_duplicate.php', $(this).serialize(), function(response) {
response = $.trim(response);
if (response == "" && response.indexOf("<") <= -1) {
$('#registration').submit(); // actually submit the form
}
else if(response.indexOf("<") == 0) {
var name = $('[name="regusername"]').val();
$('#message_line').text("Some error occured, please try after some time.");
$("#message_line").attr("tabindex",-1).focus();
} else {
var name = $('[name="regusername"]').val();
$('#message_line').text("'" + name + "' already exists, Please try different username");
$("#regusername").focus();
}
$('#busy_wait').hide();
});
});
Update3:
$(function() {
$('#registration').on('submit', function(e) {
e.preventDefault();
$('#message_line').text("");
if(!validate_fields_on_submit()) { // I assume you meant NOT
return;
}
$('#busy_wait').show();
var $thisForm=$(this); // save for later
var params = $thisForm.serialize();
$.post('check_duplicate.php', params, function(response) {
response = $.trim(response);
if (response == "" && response.indexOf("<") <= -1) {
// actually submit the form
$.post($thisForm.prop("action"), params, function(response) {
if (response.indexOf("success") !=-1) {
$('#message_line').text(response);
}
else {
$('#message_line').text("something went wrong");
}
$('#busy_wait').hide();
});
}
else if(response.indexOf("<") == 0) {
var name = $('[name="regusername"]').val();
$('#message_line').text("Some error occured, please try after some time.");
$("#message_line").attr("tabindex",-1).focus();
} else {
var name = $('[name="regusername"]').val();
$('#message_line').text("'" + name + "' already exists, Please try different username");
$("#regusername").focus();
}
$('#busy_wait').hide();
});
});
To prevent form submission the best method will be to return false on the onclick client event
Eg
$('#submit').click(function(){
return false;
})

Create and send an e-mail from a form + keep javascript filters

On the contact page, I do have a form that will allow users to send e-mails to the company. To control each field, I had a script to the form and some css effects.
This is working perfectly.
Here is a DEMO (Sadly, it can't work on jsfidle)
However, I didn't find any solution to send an e-mail with javascript (impossible). But what do I have to do to keep my javascript functionalities and send this e-mail?
Note: After sending the e-mail,the user has to stay on the same page.
HTML
<form onSubmit="return formValidation();" id="contactForm" name="contactForm" action="index.php">
<ul>
<label for="name">Name <span id="required">*</span></label>
<li><input name="name" id="name" type="text"/></li>
</ul>
<ul>
<label for="telephone">Telephone <span id="required">*</span></label>
<li><input name="telephone" id="telephone" type="text"/></li>
</ul>
<ul>
<label for="email">Email <span id="required">*</span></label>
<li><input name="email" id="email" type="text"></li>
</ul>
<ul>
<label for="message">Message <span id="required">*</span></label>
<li><textarea name="message" id="message" cols="70" rows="10" ></textarea></li>
</ul>
<ul id="row_submit_button">
<li><input type="submit" value="Submit" id="submit_button"/></li>
</ul>
<ul id="form_incorect_message">
<li>Please, fill in the form correctly.</li>
</ul>
</form>
Javascript
function formValidation()
{
var name = document.contactForm.name; // required
var telephone = document.contactForm.telephone; // required
var email = document.contactForm.email; // required
var message = document.contactForm.message; // required
fname_validation(name);
number_validation(telephone);
email_validation(email);
message_validation(message);
if (fname_validation(name)&&number_validation(telephone)&&email_validation(email)&&message_validation(message))
{
document.getElementById('form_incorect_message').style.visibility = 'hidden';
document.getElementById('contactForm').style.visibility = 'hidden';
document.getElementById('send_ok').style.display = 'block';
// sendMail();
}
else
{
}
return false;
};
function fname_validation(name)
{
if((name.value!="")&&(name.value!=" "))
{
var letters = /^[A-Za-z _-]+$/;
if(name.value.match(letters))
{
document.getElementById('name').style.borderColor = "#56D45C";
return true;
}
else
{
document.getElementById('form_incorect_message').style.visibility = "visible";
document.getElementById('name').style.borderColor = "red";
return false;
}
}
else
{
document.getElementById('form_incorect_message').style.visibility = "visible";
document.getElementById('name').style.borderColor = "red";
return false;
}
};
function message_validation(message)
{
if(message!=""&&message!=" ")
{
var letters = /^[A-Za-z0-9 _-]+$/;
if(message.value.match(letters))
{
document.getElementById('message').style.borderColor = "#56D45C";
return true;
}
else
{
document.getElementById('form_incorect_message').style.visibility = "visible";
document.getElementById('message').style.borderColor = "red";
return false;
}
}
else
{
document.getElementById('form_incorect_message').style.visibility = "visible";
document.getElementById('message').style.borderColor = "red";
return false;
}
};
function number_validation(telephone)
{
var numbers = /^[0-9+]+$/;
if(telephone.value.match(numbers))
{
document.getElementById('telephone').style.borderColor = "#56D45C";
return true;
}
else
{
document.getElementById('form_incorect_message').style.visibility = "visible";
document.getElementById('telephone').style.borderColor = "red";
return false;
}
};
function email_validation(email)
{
var mailformat = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if(email.value.match(mailformat))
{
document.getElementById('email').style.borderColor = "#56D45C";
return true;
}
else
{
document.getElementById('form_incorect_message').style.visibility = "visible";
document.getElementById('email').style.borderColor = "red";
return false;
}
};
function sendMail()
{
// var link = "mailto:my-email#gmail.com"
// + "?cc=xxxxxxx#xXXXXX.co.uk"
// + "&subject=" + escape("This is my subject")
// + "&body=" + escape(document.getElementById('myText').value);
// window.location.href = link;
};
Thanks

HTML form with 2 (hidden) submit buttons and 1 other hidden input

I'm trying to build this application that runs on Android tablets with barcode scanners attached.
The barcode scanners send an Enter after each scanned code.
I need to scan 2 barcodes and submit the form.
I created a form with two sets of input + submit button, the second one hidden. After the first barcode is scanned and the scnner send the Enter key, the hidden elements are revealed and I can scan the second barcode. However, the second time the Enter key doesn't work. It only work if I push the button (after I unhide it).
How can I take care of this so it will not need user input (other than scanning barcodes)?
Here's my code so far:
<form action="barcode.php" method="post" class="pure-form" style="width:100%">
<fieldset>
<legend>Scaneaza o fisa noua de <?php echo $operation; ?>:</legend>
<input type="text" name="barcode" autofocus id="InputID" placeholder="Codul de bare" style="width:100%;font-size:2em">
<button style="width:0;visibility:hidden;" type="submit" onclick="show_popup('my_popup'); return false;"></button>
<div id="my_popup" style="display:none;border:3px dotted gray;padding:.3em;background-color:white;position:absolute;width:80%;height:20%;margin:-50px 50px 0 50px;">
<legend>Introdu numarul de KO-uri:</legend>
<input type="text" name="kos" autofocus id="InputID" placeholder="KO-uri" style="width:100%;font-size:2em">
<button type="submit" class="pure-button pure-button-primary" style="/*width:0;visibility:hidden;*/" onclick="hide_popup('my_popup'); return true;">Trimite</button>
</div>
</fieldset>
</form>
<script type="text/javascript">
function FocusOnInput() { document.getElementById("InputID").focus(); }
function show_popup(id) {
if (document.getElementById){
obj = document.getElementById(id);
if (obj.style.display == "none") {
obj.style.display = "";
}
}
}
function hide_popup(id){
if (document.getElementById){
obj = document.getElementById(id);
if (obj.style.display == ""){
obj.style.display = "none";
}
}
}
</script>
And the barcode.php file:
<?php
ob_start();
mysql_connect ("localhost","root","root") or die (mysql_error());
mysql_select_db ("eficacitate");
$barcode = $_POST["barcode"];
$kos = $_POST["kos"];
$marca = $_COOKIE["marca"];
$operation = $_COOKIE["operation"];
if (substr($barcode,0,1)=="^") {
$j_nou = substr($barcode,1,strpos($barcode, "|")-1);
$parts = explode('|',$barcode);
$of_nou = $parts[1];
$cantitate_nou = $parts[2];
$serie_nou = $parts[3];
$adauga="INSERT INTO master (marca, operation,j,of,cantitate,serie,kos)
VALUES
('$marca','$operation','$j_nou','$of_nou','$cantitate_nou','$serie_nou','$kos')";
mysql_query($adauga);
}
header('Location: /eficacitate/scan.php');
ob_flush();
?>
Please give this a try:
<form action="barcode.php" method="post" class="pure-form" style="width:100%">
<fieldset>
<legend>Scaneaza o fisa noua de <?php echo $operation; ?>:</legend>
<input type="text" name="barcode" autofocus id="InputID" placeholder="Codul de bare" style="width:100%;font-size:2em">
<button id='barcodeButton' style="width:0;visibility:hidden;" type="submit" onclick="show_popup('my_popup'); return false;"></button>
<div id="my_popup" style="display:none;border:3px dotted gray;padding:.3em;background-color:white;position:absolute;width:80%;height:20%;margin:-50px 50px 0 50px;">
<legend>Introdu numarul de KO-uri:</legend>
<input type="text" name="kos" autofocus id="InputID" placeholder="KO-uri" style="width:100%;font-size:2em">
<button id='kosButton' type="submit" class="pure-button pure-button-primary" style="/*width:0;visibility:hidden;*/" onclick="hide_popup('my_popup'); return true;">Trimite</button>
</div>
<script type="text/javascript">
function FocusOnInput() { document.getElementById("InputID").focus(); }
document.onkeydown = function(event) {
if (event.keyCode == '13') {
barcodeButton = document.getElementById('barcodeButton');
kosButton = document.getElementById('kosButton');
if (document.getElementById('my_popup').style.display == 'none') {
barcodeButton.click();
show_popup('my_popup');
} else {
kosButton.click();
hide_popup('my_popup');
}
}
}
function show_popup(id) {
if (document.getElementById){
obj = document.getElementById(id);
if (obj.style.display == "none") {
obj.style.display = "";
}
}
}
function hide_popup(id){
if (document.getElementById){
obj = document.getElementById(id);
if (obj.style.display == ""){
obj.style.display = "none";
}
}
}
Let me know if this solves what you are trying to achive. Just out of curiosity, why aren't you using jQuery here?

Categories