Jquery validator form submitted even if invalid - php

I have a simple search form using HTML, PHP, and jQuery but the form submits even though some fields are empty and the validator warnings appear for a moment. So I would submit the form, the warnings about "Required field" appear, and it submits anyway. The validator is being triggered but isn't stopping the form.
HTML + PHP
<form action="dater.php" method="post" id="daterange">
<table width = "1000px">
<col width="250px" />
<col width="250px" />
<col width="250px" />
<col width="250px" />
<tr>
<? dateRangeView(); ?>
<td><input class="comment" type="text" name="groups" id="groupname" placeholder="Enter group name"> *</td>
<td><input class="comment" type="text" name="employee" id="staffname" placeholder="Enter employee name"> *</td>
</tr></table>
*Leave these blank to view all<br>
<button class="mainButton" id="viewTimesheets" value="viewTimesheets" type="submit">View</button>
function dateRangeView()
{
$query = "SELECT DISTINCT weekending FROM payroll_ts ORDER BY weeke DESC";
$result = mysql_query($query);
echo'<td><select id="startdate" class="infotable" name="startdate"><option value="">---- Start date ----</option>';
while ($row = mysql_fetch_array($result))
{
echo'<option value="'.$row{'weeke'}.'">'.$row{'weeke'}.'</option>';
}
echo'</select><br><td><select id="enddate" class="infotable" name="enddate"> <option value="">---- End date ----</option>';
$query = "SELECT DISTINCT weekending FROM payroll_ts ORDER BY weeke DESC";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result))
{
echo'<option value="'.$row{'weeke'}.'">'.$row{'weeke'}.'</option>';
}
echo'</select><br></td>';
}
VALIDATOR PLUGIN CODE
<script language="javascript" type="text/javascript">
/*-------------Validator-------------*/
$.validator.setDefaults({
submitHandler: function() { alert("submitted!");
form.submit();}
});
$(function() {
$("#daterange").validate({
rules: {
startdate: "required",
enddate: "required"
},
messages: {
startdate: "required",
enddate: "required"
}
});
});
</script>
I've been at it for four hours now, used .on(), return false; onSubmit() and e.preventDefault(); although I may have gotten the syntax on those messed up... This is the plugin I'm using... http://jqueryvalidation.org/validate/

Try this.
$(document).ready(function () {
$.validator.setDefaults({
submitHandler: function (form) {
alert('submitted');
form.submit();
}
});
$('#daterange').validate({
rules: {
startdate: {
required: true
},
enddate: {
required: true
}
}
});
});
Working JsFiddle example Demo
Hope this helps, Thank you
or here is the code for you both works
$(document).ready(function () {
$.validator.setDefaults({
submitHandler: function() { alert("submitted!");
form.submit();}
});
$(function() {
$("#daterange").validate({
rules: {
startdate: "required",
enddate: "required"
},
messages: {
startdate: "required",
enddate: "required"
}
});
});
});

$(document).ready(function () {
$("#daterange").validate({
rules: {
startdate: "required",
enddate: "required"
},
messages: {
startdate: "required",
enddate: "required"
}
});
if($("#daterange").valid()) {
// call your function;
alert("submitted!");
}
});

Related

Jquery Validation in CkEditor

I have seen this example and applied it in my code yet nothing worked, its not working.
Referral ans-1
Referral ans-2
I need to apply jquery validation in ckeditor and I have seen all those past examples even I have mentioned those links above, by doing that step my validation is still not working.
Here is my HTML Code
<div class="elementbox">
<label class="form-label">Content<span class="required">*</span></label>
<div class="controls">
<textarea name="content_body" id="content_body" rows="10" cols="80"><?php echo $content_body; ?></textarea>
</div>
</div>
<script>
var url = "<?php echo base_url(); ?>";
CKEDITOR.replace( 'content_body',{
//extraPlugins: 'imageuploader'
} );
</script>
My Jquery validation code
$("#add_content_pages").validate({
ignore: [],
debug: false,
rules: {
title: {
required: true
},
content_id: {
required: true
},
content_body:{
required: function()
{
CKEDITOR.instances.content_body.updateElement();
}
}
},
messages: {
title: {
required: "Please enter Title"
},
content_id: {
required: "Please Select Content Type"
},
content_body: {
required: "Please enter Content"
}
},
errorPlacement: function (error, element) {
var attr_name = element.attr('name');
if (attr_name == 'type') {
error.appendTo('.type_err');
} else {
error.insertAfter(element);
}
}
});
Any Solution what I am missing?
please check this code
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.15.0/jquery.validate.min.js"></script>
<script src="https://cdn.ckeditor.com/4.6.2/standard/ckeditor.js"></script>
then html form
<form action="" method="post" id="check_form">
<div class="elementbox">
<label class="form-label">Content<span class="required">*</span></label>
<div class="controls">
<textarea name="content_body" id="content_body" rows="10" cols="80"></textarea>
<div id="error_check_editor"></div>
</div>
</div>
<script>
CKEDITOR.replace('content_body');
</script>
<br/>
<input name="submit" type="submit" value="Submit" class="button" id="submit"/>
</form>
then script
<script>
$.validator.addMethod("check_ck_add_method",
function (value, element) {
return check_ck_editor();
});
function check_ck_editor() {
if (CKEDITOR.instances.content_body.getData() == '') {
return false;
}
else {
$("#error_check_editor").empty();
return true;
}
}
$(document).ready(function () {
$("#check_form").validate(
{
ignore: [],
debug: false,
errorPlacement: function (error, element) {
if (element.attr("name") == "content_body") {
error.insertAfter(element);
}
},
rules: {
content_body: {
check_ck_add_method: true
}
},
messages: {
content_body: {}
}
});
});
</script>

jQuery Validation - Remote function with additional data

I am having issues with validating some data.
I want to check if someone has reviewed a company before by checking for the company_id and the logged in users account_number in my reviews table.
The code I currently has doesn't ever seem to find anything in the reviews table so doesn't warn people they can't submit another review.
Your help to get this working is much appreciated.
Here is the code I have so far:
Form
<form name="review" id="review" method="post" action="/db_processing/reviews/process-reviews.php">
<input type="hidden" value="<?php echo($results['company_id']) ?>" name="company_id" />
<input type="hidden" value="<?php echo($_SESSION["ID"]) ?>" name="account_number" />
<p class="cs-threequarter">
<b>Comments:</b><br>
<textarea name="comments" style="width:95%; height: 150px"></textarea>
</p>
<p class="cs-quarter">
<b>Rating:</b>
<span class="star-rating">
<input type="radio" name="rating" value="1"><i></i>
<input type="radio" name="rating" value="2"><i></i>
<input type="radio" name="rating" value="3"><i></i>
<input type="radio" name="rating" value="4"><i></i>
<input type="radio" name="rating" value="5"><i></i>
</span>
</p>
<p><input class="cs-btn cs-red" name="submit" type="submit" value="Submit Review!"></p>
<div class="cs-container"></div>
<div class="cs-error-note" id="cs-error-note3"></div>
</form>
<script src="/js/validation/reviewval.js"></script>
jQuery Validation Script
$(document).ready(function () {
$('#review').validate({
errorLabelContainer: "#cs-error-note3",
wrapper: "li",
ignore: "not:hidden",
rules: {
comments: {
required: true
},
account_number: {
required: true,
remote: {
url: "/db_processing/reviews/check-account.php",
type: "post",
data: {
company_id: function() {
return $("#company_id").val();
}
}, }
},
rating: {
required: true
}
},
messages: {
comments: {
required: "Please enter some comments."
},
account_number: {
required: "You must be logged in to review.",
remote: "You have already reviewed this company."
},
rating: {
required: "Please select a rating."
}
},
submitHandler: function(form) {
form.submit();
}
});
});
Check-account.php
<?php
require('../../../private_html/db_connection/connection.php');
$conn = new PDO("mysql:host=$servername; dbname=$dbname", $username, $password);
if(isset($_POST['account_number'])) {
$account_number = $_POST['account_number'];
$compid = $_POST['company_id'];
$query = $conn->prepare("SELECT account_number FROM reviews WHERE account_number =$account_number && company_id =$compid");
$query->execute();
$rows = $query->fetchAll();
$total_rows = count($rows);
if( $total_rows > 0 ){
echo 'false';
} else {
echo 'true';
}
}
?>
Validation code working fine, there is no problem expect unnecessary comma ,. remove it, Not all browsers are very forgiving.
$(document).ready(function () {
$('#review').validate({
errorLabelContainer: "#cs-error-note3",
wrapper: "li"
ignore: "not:hidden",
rules: {
comments:
required: true
},
account_number: {
required: true,
remote: {
url: "/db_processing/reviews/check-account.php",
type: "post",
data: {
company_id: function() {
return $("#company_id").val();
}
}, //<-----Remove this, it's unnecessary
}
},
rating: {
required: true
}
},
messages: {
comments: {
required: "Please enter some comments."
},
account_number: {
required: "You must be logged in to review.",
remote: "You have already reviewed this company."
},
rating: {
required: "Please select a rating."
}
},
submitHandler: function(form) {
form.submit();
}
});
});
HTML
The problem is here, because of it validation and query both failing.
<input type="hidden" value="<?php echo($results['company_id']) ?>" name="company_id" />
assign id to this input because you are fetching it's value with id selector in validation script here return $("#company_id").val(); so it will be
<input type="hidden" value="<?php echo($results['company_id']) ?>" name="company_id" id="company_id" />
last in PHP
put quotes ' around variables inside query, rest is all good and working.
$query = $conn->prepare("SELECT account_number FROM reviews WHERE account_number = '$account_number' && company_id = '$compid'");

Use jQuery validation on anchor tag click

I want to use jQuery validation on anchor tag click event. Here is my HTML form and jquery
HTML Form :
<form name="search_booking" id="search_booking" action="get_booking_by_cust_name.php" method="POST">
<input type="text" name="job_date" id="job_date">
<a id="submit" style="cursor: pointer" >Search</a>
</form>
jQuery Code:
$(document).ready(function () {
$("#submit").click(function () {
$("#search_booking").validate({
rules: {
job_date: {required: true}
},
messages: {
job_date: {
required: "Please provide job date."
}
},
submitHandler: function (form) {
form.submit();
}
});
});
});
After clicking on anchor tag it will not submitting form to the form action.
Thanks in advance.
You need to initialize the validator plugin in dom ready and then in the submit button click, call the form's submit event which will do the validation.
$(document).ready(function() {
$("#search_booking").validate({
rules: {
job_date: {
required: true
}
},
messages: {
job_date: {
required: "Please provide job date."
}
},
submitHandler: function(form) {
form.submit();
}
});
$("#submit").click(function() {
$("#search_booking").submit();
});
});
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.12.0/jquery.validate.js"></script>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.12.0/additional-methods.js"></script>
<form name="search_booking" id="search_booking" action="get_booking_by_cust_name.php" method="POST">
<input type="text" name="job_date" id="job_date">
<a id="submit" style="cursor: pointer">Search</a>
</form>
This is very similar to the accepted answer except for two things...
I'm using an event.preventDefault() to block the default behaviors of the anchor element.
$("#submit").click(function(e) {
e.preventDefault();
$("#search_booking").submit();
});
I've added a href="#" so that the jump to the top of the page can be properly blocked by the .preventDefault(), as well as to maintain HTML standards compliance.
<a id="submit" href="#" style="cursor: pointer">Search</a>
$(document).ready(function() {
$("#search_booking").validate({
rules: {
job_date: {
required: true
}
},
messages: {
job_date: {
required: "Please provide job date."
}
},
submitHandler: function(form) {
// form.submit(); //default plugin behavior
alert('submission'); // only for demo
}
});
$("#submit").click(function(e) {
e.preventDefault();
$("#search_booking").submit();
});
});
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.12.0/jquery.validate.js"></script>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.12.0/additional-methods.js"></script>
<form name="search_booking" id="search_booking" action="get_booking_by_cust_name.php" method="POST">
<input type="text" name="job_date" id="job_date">
<a id="submit" href="#" style="cursor: pointer">Search</a>
</form>

How do I post HTML form data to a php file another server using jQuery

I am a bit of a noob with jQuery and am learning for Uni.
I am working on a HTML web site with an associated HTML mobile application that I will compile in phonegap build.
I have a HTML form that I want to include on both the site and the app which I have coded and is successfully validating with jQuery. I would also like to post the form data with jQuery but am struggling to find how best to achieve this.
My form looks like this
<form action="http://myaddress.com/process.php" method="post" name="jform" id="jform">
<div>
<label for="name"><b>Name:</b></label><br>
<input type="text" name="name" id="name">
</div>
<div>
<label for="dob"><b>Date of Birth:</b></label><br>
<input type="text" name="dob" id="dob">
</div>
<div>
<label for="visit"><b>Date of Visit:</b></label><br>
<input type="text" name="visit" id="visit">
</div>
<div class="labelBlock">
<b>Favourite Exhibit:</b>
<div class="indent">
<input type="radio" name="fave" id="exhibit1" value="Exhibit1">
<label for="exhibit1">Exhibit 1</label><br>
<input type="radio" name="fave" id="exhibit2" value="Exhibit2">
<label for="exhibit2">Exhibit 2</label><br>
<input type="radio" name="fave" id="exhibit3" value="Exhibit3">
<label for="exhibit3">Exhibit 3</label>
</div>
</div>
<div>
<label for="comment"><b>Comments:</b></label><br>
<textarea name="comment" id="comment" rows="10" cols="40" draggable="false"></textarea>
</div>
<div id="center-button">
<input name="submit" type="submit" id="submit" value="Submit" class="center-text">
</div>
</form>
My validation script looks like this:
<script>
$(document).ready(function() {
$('#jform').validate({
rules: {
name: "required",
dob: "required",
visit: "required",
fave: "required",
comment: "required"
}, //end rules
messages: {
name: {
required: "Please tell us your name"
},
dob: {
required: 'Please select your Date of Birth'
},
visit: {
required: 'Please select the date you visited'
},
fave: {
required: 'Please select your favourite exhibit'
},
comment: {
required: 'Please tell us about your visit'
}
},//end messages
errorPlacement: function(error, element) {
if ( element.is(":radio") ) {
error.appendTo( element.parent());
} else {
error.insertAfter(element);
}
}
}); // end validate
submitHandler: function(form) { //This is the submit handler.
var name = $('#name').val();
var dob = $('#dob').val();
var visit = $('#visit').val();
var fave = $("input[name='fave']:radio:checked").val();
var comment = $('#comment').val();
$.ajax({
type: 'POST',
url: 'process-post.php',
data: {name:name, dob:dob, visit:visit, fave:fave, comment:comment},
success: function(data1){
if (data1 == 'success') {
window.location.href = 'index.html';
}
else {
alert('Oops! It looks like something has gone wrong. Please try again.');
}
}
});
}}); // end ready
I really am struggling with this so would appreciate any help.
My PHP Looks like this
<?php # PROCESS JOURNAL ENTRY.
# Check form submitted.
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
# Open database connection.
require ( '../connect_db.php' ) ;
# Execute inserting into 'forum' database table.
$q = "INSERT INTO journal(name,dob,visit,fave,comment,date)
VALUES ('{$_POST[name]}','{$_POST[dob]}','{$_POST[visit]}','{$_POST[fave]}','{$_POST [comment]}',NOW() )";
$r = mysqli_query ( $dbc, $q ) ;
# Report error on failure.
if (mysqli_affected_rows($dbc) != 1) { die ('Error' . mysqli_error($dbc)); } else { echo "success"; }
# Close database connection.
mysqli_close( $dbc ) ;
}
?>
Yes he is correct jquery's ajax will accomplish this or http post. You will use one of the mentioned methods to get the data from the HTML form and send it to the sever.
You will need jQuery ajax. This is a very powerful function that is used any time jQuery validation is used. It also lets you submit to the PHP file and get the results without refreshing the page.
EDIT:
Depending on the complexity of your project, ajax may be overkill. You can just normally submit the form after it is validated like this:
<script>
$(document).ready(function() {
$('#jform').validate({
rules: {
name: "required",
dob: "required",
visit: "required",
fave: "required",
comment: "required"
}, //end rules
messages: {
name: {
required: "Please tell us your name"
},
dob: {
required: 'Please select your Date of Birth'
},
visit: {
required: 'Please select the date you visited'
},
fave: {
required: 'Please select your favourite exhibit'
},
comment: {
required: 'Please tell us about your visit'
}
},//end messages
errorPlacement: function(error, element) {
if ( element.is(":radio") ) {
error.appendTo( element.parent());
} else {
error.insertAfter(element);
}
}
}); // end validate
submitHandler: function(form) { //This is the submit handler.
$(form).submit();
}
}); // end ready
</script>
Here is the part that I add:
submitHandler: function(form) { //This is the submit handler.
$(form).submit();
}
This will submit a form normally, meaning that it will run the PHP script and then refresh the page.
If you decide you want to use ajax, you can just replace $(form).submit(); with this:
var name = $('#name').val();
var dob= $('#dob').val();
var visit = $('#visit').val();
var fave = $("input[type='radio'][name='fave']:checked").val();
var comment = $('#comment').val();
$.ajax({
type: 'POST',
url: 'http://myaddress.com/process.php',
data: {name:name, dob:dob, visit:visit, fave:fave, comment:comment},
success: function(data){
if (data == 'success') {
//do something
}
else {
//do something
}
}
});
The data that I am using in the success portion of the function is the value returned from the PHP script. Since you mentioned comments, I am assuming that you PHP is not returning data, but more or less a completion message. In that case, you would just have your PHP echo 'success'; if it was successful. Then fill in the "do somethings" in the jQuery.

Checking field is blank or not to upload image file

I can't validate upload field. the field name is an array. how to validate it using jquery?
here is my code:
<script type="text/javascript">
$().ready(function() {
// validate signup form on keyup and submit
var validator = $("#signupform").submit(function() {
// update underlying textarea before submit validation
}).validate({
rules: {
name: "required",
photo_path: { required: true }
},
errorPlacement: function(label, element) {
label.insertAfter(element);
},
messages: {
name: "Please enter your name",
photo_path: "Upload your Image"
}
});
});
</script>
<?php
$count=1;
for($i=0; $i<4; $i++)
{
?>
<input type="hidden" name="galleryImage[]" id="galleryImage[]" value="<?=$i?>"/> </td>
</tr>
<tr>
<td align="left" valign="middle" bordercolor="1" class="signup">Upload Image <?=$count?>:</td>
<td align="left" valign="middle" bordercolor="1"><input type="file" name="photo_path[]" id="photo_path" class="inputcolor_text" />
<br />
<?php
$count++;
}
?>
Give this a go...
var validator = $("#signupform").submit(function(e) {
if(!$('.inputcolor_text').val()){
e.preventDefault();
// $('#error').html('Cannot be empty.');
return false;
}
}).validate.....

Categories