Validate form using jqueryvalidate.js and ckeditor Codeigniter - javascript

Hello. I have a form that gets validated by jqueryvalidate.js. I have a drop down menu and the menu will be different when I choose "Library Asset" because I need to choose another drop down menu that is hidden.
The problem is, when I am not choose other menu that is not showing another drop down menu..
the required rules still implemented.. so the form can't be submitted except the one that is showing another drop down menu..
Can someone help me here?
This is my code:
View(Js):
<script type="text/javascript">
function showbook()
{
var domObj1 = document.getElementById('emptybox');
var domObj2 = document.getElementById('showupbox');
if(domObj1.style.display =='none')
{
domObj1.style.display = 'block';
domObj2.style.display = 'none';
}
else
{
domObj1.style.display = 'none';
domObj2.style.display = 'block';
}
}
function closebook()
{
var domObj1 = document.getElementById('emptybox');
var domObj2 = document.getElementById('showupbox');
if(domObj1.style.display =='none')
{
domObj1.style.display = 'block';
domObj2.style.display = 'none';
}
}
function showhidebook()
{
console.log($('#CategoryAdviceSelect').val());
if($('#CategoryAdviceSelect').val() == 1)
{
showbook();
}
else{
closebook();
}
}
My validation rules:
<script>
$().ready(function() {
$("#feedback_form").validate({
ignore: "input:hidden:not(input:hidden.required)",
rules: {
CategoryAdviceSelect:"required",
Subject:"required",
Advice:"required",
BookSelect:"required"
},
messages: {
CategoryAdviceSelect:"Please select one of category advice",
Subject:"This field is required",
Advice:"This field is required",
BookSelect:"This field is required"
},
errorElement: "span",
highlight: function(element) {
$(element).parent().addClass("help-block");
},
unhighlight: function(element) {
$(element).parent().removeClass("help-block");
}
});
});
</script>
And my html view
<div class="row-fluid ">
<div class="box">
<hr>
<div class="paragraph">
<p>For enquiries about our services, write to: helpdesk#library.binus.ac.id.</p>
<p>You may also reach us at our helpdesk number 62-21-5350660. We value your feedback. Please fill in the form below, and help us improve our services.</p>
<p>Talk to me here
<a href = 'ymsgr:sendim?me_lieza93'>
<img src="http://opi.yahoo.com/online?u=me_lieza93&m=g&t=1" border=0>
</a>
</p>
</div>
<!--START FORM-->
<form id="feedback_form" name="feedback_form" action="<?php echo base_url();?>feedback/feedback/insert_to_db" method="post" class="form-horizontal" novalidate="novalidate">
<div class="control-group">
<!--FEEDBACK TYPE-->
<label class="span2 control-label" >Feedback for</label>
<div class="controls with-tooltip">
<select class="input-tooltip span5" tabindex="2" id="CategoryAdviceSelect" name="CategoryAdviceSelect" onchange="showhidebook();" >
<option value="" disabled selected>Choose Your Feedback For..</option>
<?php
for($x = 0 ; $x < count($feedback) ; $x++)
{ ?>
<option value="<?php echo $feedback[$x]['CategoryAdviceId']?>"><?php echo $feedback[$x]['CategoryAdviceName'] ?></option>
<?php
} ?>
</select>
</div>
</div>
<!--SUBJECT-->
<div class="control-group">
<label for="limiter" class="control-label">Subject</label>
<div class="controls">
<input type="text" class="span5" maxlength="50" id="Subject" name="Subject" placeholder="Type Your Feedback Subject.." />
<p class="help-block"></p>
</div>
</div>
<div id="emptybox"></div>
<!--CHOOSE BOOK-->
<div id="showupbox" style="display: none;">
<div class="control-group">
<label class="control-label">Choose Book</label>
<div class="controls">
<select class="chzn-select span5" tabindex="2" id="BookSelect" name="BookSelect">
<option value="" disabled selected>Choose Your Feedback For..</option>
<?php
for($y = 0 ; $y < count($booklist) ; $y++)
{ ?>
<option value="<?php echo $booklist[$y]['bi']?>"><?php echo $booklist[$y]['AssetTitle']?></option>
<?php
} ?>
</select>
</div>
</div>
</div>
<!--ADVICE-->
<div class="control-group">
<label for="limiter" class="control-label" >Suggestion</label>
<div class="controls">
<?php echo $this->ckeditor->editor("Advice",""); ?>;
</div>
</div>
<!--div class="alert alert-success">
<a class="close" data-dismiss="alert">×</a>
<strong>Success!</strong> Thanks for your feedback!
</div-->
<div class="bton1">
<button class="btn btn-primary round" type="submit">Submit</button>
<button class="btn btn-primary round" type="refresh">Reset</button>
</div>
</form>
</div><!--END BOX-->

Finally I can solve this..
<script>
$(document).ready(function() {
for(var name in CKEDITOR.instances) {
CKEDITOR.instances["Advice"].on("instanceReady", function() {
// Set keyup event
this.document.on("keyup", updateValue);
// Set paste event
this.document.on("paste", updateValue);
});
function updateValue() {
CKEDITOR.instances["Advice"].updateElement();
$('textarea').trigger('keyup');
}
}
$("#feedback_form").validate({
ignore: 'input:hidden:not(input:hidden.required)',
rules: {
CategoryAdviceSelect:"required",
Subject:"required",
Advice:"required",
BookSelect:{
required: function(element){
return $("#CategoryAdviceSelect").val()==1;
}
}
},
messages: {
CategoryAdviceSelect:"Please select one of category advice",
Subject:"This field is required",
Advice:"This field is required",
BookSelect:"This field is required",
},
errorElement: "span",
errorPlacement: function (error, element) {
if ($(element).attr('name') == 'Advice') {
$('#cke_Advice').after(error);
} else {
element.after(error);
}
},
highlight: function(element) {
$(element).parent().addClass("help-block");
},
unhighlight: function(element) {
$(element).parent().removeClass("help-block");
}
});
});
</script>

Related

How to retrieve the last inserted id from another method inside same class?

I have two methods inside Home class called addProperty and uploadImages.
I'm calling the uploadImages() method from the jquery dropzone to post the images and addProperty() for inserting the form inputs into the database.
I want to pass the last inserted Id from the addProperty method to uploadImages to save the image details into the database.
Home.php (Controller)
<?php if(!defined('BASEPATH')) exit('No direct script access allowed');
class Home extends CI_Controller
{
/**
* This is default constructor of the class
*/
public function __construct()
{
parent::__construct();
$this->load->model('property_model');
}
/**
* Index Page for this controller.
*/
public function index()
{
$data = array('title'=> 'Vierra Property Broker', 'main_content'=>'home');
$this->load->view('template', $data);
}
/**
* Loaading the submit property form.
*/
public function listProperty()
{
$data = array('title'=> 'Vierra Property Broker - Submit your Property', 'main_content'=>'submit_property');
$this->load->view('template', $data);
}
function addProperty()
{
$this->load->library('form_validation');
//$this->form_validation->set_rules('prop_title','Villa Title','trim|required|max_length[128]');
// $this->form_validation->set_rules('prop_status','Status','trim|required');
//$this->form_validation->set_rules('prop_type','Type','trim|required');
//$this->form_validation->set_rules('prop_price','Price','trim|required|numeric');
//$this->form_validation->set_rules('prop_sqft','Sqft','trim|required|numeric');
$this->form_validation->set_rules('prop_rooms','Rooms','trim|required|numeric');
$this->form_validation->set_rules('prop_address','Address','trim|required|max_length[200]');
$this->form_validation->set_rules('prop_owner_phone','Mobile Number','required|min_length[10]');
$this->form_validation->set_rules('prop_owner_name','Owner Name','required|min_length[5]');
$this->form_validation->set_rules('prop_owner_email','Owner Email','required|valid_email');
//$this->form_validation->set_rules('prop_detailed_info','Detailed Info','trim|required|max_length[2000]');
//$this->form_validation->set_rules('prop_status','Current Status','trim|required');
if($this->form_validation->run() == FALSE)
{
$this->listProperty();
}
else
{
$prop_title = ucwords(strtolower($this->security->xss_clean($this->input->post('prop_title'))));
$prop_status = ucwords(strtolower($this->security->xss_clean($this->input->post('prop_status'))));
$prop_type = ucwords(strtolower($this->security->xss_clean($this->input->post('prop_type'))));
$prop_price = $this->security->xss_clean($this->input->post('prop_price'));
$prop_sqft = $this->security->xss_clean($this->input->post('prop_sqft'));
$prop_rooms = $this->security->xss_clean($this->input->post('prop_rooms'));
$prop_address = $this->security->xss_clean($this->input->post('prop_address'));
$prop_owner_name = $this->security->xss_clean($this->input->post('prop_owner_name'));
$prop_owner_email = $this->security->xss_clean($this->input->post('prop_owner_email'));
$prop_owner_phone = $this->security->xss_clean($this->input->post('prop_owner_phone'));
$prop_detailed_info = $this->security->xss_clean($this->input->post('prop_detailed_info'));
$prop_current_status = $this->security->xss_clean($this->input->post('prop_current_status'));
//$userInfo = array('email'=>$email, 'password'=>getHashedPassword($password), 'roleId'=>$roleId, 'name'=> $name,
//'mobile'=>$mobile, 'createdBy'=>$this->vendorId, 'createdDtm'=>date('Y-m-d H:i:s'));
$propertyInfo = array('title'=>$prop_title, 'status'=>$prop_status, 'type'=>$prop_type, 'price'=>$prop_price,
'sqft'=>$prop_sqft, 'rooms'=>$prop_rooms, 'address'=>$prop_address, 'name'=>$prop_owner_name,
'email'=>$prop_owner_email, 'phone'=>$prop_owner_phone, 'detailedInfo'=>$prop_detailed_info,
'currentStatus'=>$prop_current_status);
$this->load->model('property_model');
$result = $this->property_model->addNewProperty($propertyInfo);
if($result > 0)
{
//$propertyImgUpload = uploadImages($result);
$this->session->set_flashdata('success', 'Thank you for submiting your property with us!, Our team will contact you shortly');
}
else
{
$this->session->set_flashdata('error', 'Submission of property failed, Contact wasim#vpd.ae');
}
redirect('/submit-property');
}
}
function uploadImage($propertyid)
{
if (!empty($_FILES)) {
$count_img = count($_FILES['file']['name']);
foreach($_FILES['file']['tmp_name'] as $key => $value) {
$tempFile = $_FILES['file']['tmp_name'][$key];
$fileName = $_FILES['file']['name'][$key];
$targetPath = 'property-images/';
$targetFile = $targetPath . $fileName ;
if(move_uploaded_file($tempFile, $targetFile))
{
$response = "Success";
}
else {
$response = "Failed";
}
}
}
}
}
?>
addProperty.js (Jquery validating & post dropzone images to uploadImages() method
/**
* File : addUser.js
*
* This file contain the validation of add user form
*
* Using validation plugin : jquery.validate.js
*
* #author Sarath Chandran
*/
$(document).ready(function(){
$("#error_msg").hide();
var addPropertyForm = $("#property-form");
var validator = addPropertyForm.validate({
rules:{
//prop_title :{ required : true },
//prop_status : { required : true, selected : true },
//prop_type : {required : true, selected: true },
prop_rooms : {required : true, selected: true },
prop_address :{ required : true },
prop_owner_name :{ required : true },
//prop_detailed_info :{ required : true },
prop_owner_email :{ required : true, email : true },
prop_owner_phone :{ required : true, digits : true },
//prop_price : { required : true, digits : true },
//prop_sqft : { required : true, digits : true }
},
messages:{
//prop_title :{ required : "Please enter title of villa" },
//prop_status : { required : "Please select status", selected : "Please select atlease one option" },
//prop_type : { required : "Please select type of villa", selected : "Please select atlease one option" },
prop_rooms : { required : "Please select bed rooms", selected : "Please select atlease one option" },
prop_address : { required : "Please enter address of villa"},
prop_owner_name : { required : "Please enter name of owner"},
prop_owner_email : { required : "Please enter email of owner", email : "Please enter valid email"},
prop_owner_phone : { required : "Please enter phone of owner", digits : "Please enter valid phone no"},
//prop_price : { required : "Please enter price of villa", digits : "Please enter price in digits"},
//prop_detailed_info : { required : "Please enter detailed information"},
//prop_sqft : { required : "Please enter size of villa", digits : "Please enter size in Sqft"}
},
})
Dropzone.autoDiscover = false;
$("div#myDropzone").dropzone({
url: 'image-upload',
addRemoveLinks: true,
paramName: "file",
maxFiles:11,
autoProcessQueue: false,
uploadMultiple: true,
acceptedFiles: "image/*",
maxFilesize: 1,
parallelUploads: 10,
init: function () {
var myDropzone = this;
$("#property-form").submit(function (e) {
$(window).scrollTop(0);
//e.preventDefault();
if ( $("#property-form").valid() ) {
myDropzone.processQueue();
}
});
this.on('sending', function(file, xhr) {
// Append all form inputs to the formData Dropzone will POST
//alert("Data is sending");
});
this.on("complete", function (file) {
if (this.getUploadingFiles().length === 0 && this.getQueuedFiles().length === 0) {
//alert("Completed Upload");
$("#property-form").submit();
}
});
}
});
});
submit_property.php (View)
<div class="content-area-7 submit-property">
<div class="container">
<div class="row">
<div class="col-md-12">
<!-- <div id="error_message" class="notification-box"></div> -->
</div>
<?php
$this->load->helper('form');
$error = $this->session->flashdata('error');
if($error)
{
echo '<div class="notification-box">'.$error.'</div>';
}
$success = $this->session->flashdata('success');
if($success)
{
echo '<div class="notification-box">'.$success.'</div>';
}
?>
<div id="error_msg" class="alert alert-danger wow fadeInRight delay-01s" role="alert" style="visibility: visible; animation-name: fadeInRight;">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
<strong>Oops!</strong>, Please fix the following errors and submit again
</div>
<div class="col-md-12">
<div class="submit-address">
<form name = "property-form" action="<?php echo base_url() ?>list-property" method="post" id="property-form">
<div class="main-title-2">
<h1><span>Tell Me</span> Something About Your Property</h1>
</div>
<div class="search-contents-sidebar mb-30">
<div class="form-group">
<label>Property Title</label>
<input class="input-text" name="prop_title" id="prop_title" placeholder="Property Title">
<?php echo form_error('prop_title'); ?>
</div>
<div class="row">
<div class="col-md-6 col-sm-6">
<div class="form-group">
<label>Status</label>
<select class="form-control required" id="prop_status" name="prop_status">
<option value="">Select</option>
<option value="Sale">For Sale</option>
<option value="Rent">For Rent</option>
</select>
</div>
</div>
<div class="col-md-6 col-sm-6">
<div class="form-group">
<label>Type</label>
<select class="form-control required" id="prop_type" name="prop_type">
<option value="">Select</option>
<option value="Modern">Modern</option>
<option value="Traditional">Traditional</option>
<option value="Arabic">Arabic</option>
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-md-3 col-sm-6">
<div class="form-group">
<label>Price (Dirham)</label>
<input class="input-text" name="prop_price" id="prop_price" placeholder="AED">
<?php echo form_error('prop_price'); ?>
</div>
</div>
<div class="col-md-3 col-sm-6">
<div class="form-group">
<label>Sqft</label>
<input class="input-text" name="prop_sqft" id="prop_sqft" placeholder="SqFt">
<?php echo form_error('prop_sqft'); ?>
</div>
</div>
<div class="col-md-3 col-sm-6">
<div class="form-group">
<label>Bed Rooms</label>
<select class="form-control required" name="prop_rooms" id="prop_rooms">
<option value="">Select</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
</div>
</div>
<!-- <div class="col-md-3 col-sm-6">
<div class="form-group">
<label>Bathroom</label>
<select class="selectpicker search-fields" name="1">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
<option>6</option>
</select>
</div>
</div> -->
</div>
</div>
<div class="main-title-2">
<h1><span>Location</span></h1>
</div>
<div class="row mb-30 ">
<div class="col-md-6 col-sm-6">
<div class="form-group">
<label>Address</label>
<input class="input-text" id="prop_address" name="prop_address" placeholder="Address">
</div>
<?php echo form_error('prop_address'); ?>
</div>
</div>
<div class="main-title-2">
<h1><span>Contact</span> Details</h1>
</div>
<div class="row">
<div class="col-md-4 col-sm-4">
<div class="form-group">
<label>Name</label>
<input class="input-text" name="prop_owner_name" id="prop_owner_name" placeholder="Name">
<?php echo form_error('prop_owner_name'); ?>
</div>
</div>
<div class="col-md-4 col-sm-4">
<div class="form-group">
<label>Email</label>
<input class="input-text" name="prop_owner_email" id="prop_owner_email" placeholder="Email">
<?php echo form_error('prop_owner_email'); ?>
</div>
</div>
<div class="col-md-4 col-sm-4">
<div class="form-group">
<label>Contact No</label>
<input class="input-text" name="prop_owner_phone" id="prop_owner_phone" placeholder="Phone">
<?php echo form_error('prop_owner_phone'); ?>
</div>
</div>
</div>
<div class="main-title-2">
<h1><span>Upload</span> Photos Of Villa </h1>
</div>
<div id="myDropzone" class="dropzone dropzone-design mb-10">
<div class="dz-default dz-message" data=""><span>Drop files here to upload</span></div>
</div>
<div class="main-title-2">
<h1><span>Detailed</span> Information</h1>
</div>
<div class="row mb-30">
<div class="col-md-12">
<div class="form-group">
<textarea class="input-text" id="prop_detailed_info" name="prop_detailed_info" placeholder="Detailed Information"></textarea>
</div>
<?php echo form_error('prop_detailed_info'); ?>
</div>
</div>
</div>
<div class="col-md-12">
<input type="submit" class="btn button-sm button-theme" value="Submit" />
</div>
<script src="<?php echo base_url('assets/frontend/js/addProperty.js'); ?>"></script>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
Property_model.php (Model)
<?php if(!defined('BASEPATH')) exit('No direct script access allowed');
/**
* Class : User_model (User Model)
* User model class to get to handle user related data
* #author : Kishor Mali
* #version : 1.1
* #since : 15 November 2016
*/
class Property_model extends CI_Model
{
/**
* This function is used to get the user listing count
* #param string $searchText : This is optional search text
* #return number $count : This is row count
*/
function propertyListingCount($searchText = '')
{
$this->db->select('BaseTbl.propertyid, BaseTbl.title, BaseTbl.status, BaseTbl.type, BaseTbl.price, BaseTbl.phone');
$this->db->from('tbl_properties as BaseTbl');
if(!empty($searchText)) {
$likeCriteria = "(BaseTbl.email LIKE '%".$searchText."%'
OR BaseTbl.name LIKE '%".$searchText."%'
OR BaseTbl.phone LIKE '%".$searchText."%')";
$this->db->where($likeCriteria);
}
$this->db->where('BaseTbl.currentStatus', 0);
$query = $this->db->get();
return $query->num_rows();
}
/**
* This function is used to get the user listing count
* #param string $searchText : This is optional search text
* #param number $page : This is pagination offset
* #param number $segment : This is pagination limit
* #return array $result : This is result
*/
function propertyListing($searchText = '', $page, $segment)
{
$this->db->select('BaseTbl.propertyid, BaseTbl.title, BaseTbl.status, BaseTbl.type, BaseTbl.price, BaseTbl.phone');
$this->db->from('tbl_properties as BaseTbl');
if(!empty($searchText)) {
$likeCriteria = "(BaseTbl.email LIKE '%".$searchText."%'
OR BaseTbl.name LIKE '%".$searchText."%'
OR BaseTbl.phone LIKE '%".$searchText."%')";
$this->db->where($likeCriteria);
}
$this->db->where('BaseTbl.currentStatus', 0);
$this->db->order_by('BaseTbl.propertyid', 'DESC');
$this->db->limit($page, $segment);
$query = $this->db->get();
$result = $query->result();
return $result;
}
/**
* This function is used to add new property to system
* #return number $insert_id : This is last inserted id
*/
function addNewProperty($propertyInfo)
{
$this->db->trans_start();
$this->db->insert('tbl_properties', $propertyInfo);
$insert_id = $this->db->insert_id();
$this->db->trans_complete();
return $insert_id;
}
function addPropertyImgs($propertyImgs)
{
$this->db->trans_start();
$this->db->insert('tbl_property_images', $propertyImgs);
$insert_id = $this->db->insert_id();
$this->db->trans_complete();
return $insert_id;
}
}
?>
I want to insert the image details into the table called tbl_property_images
File Upload working
Form inputs also successfully inserted
Problem :
I need to insert image details to the table with the propertyid, The propertyid is the last inserted id we get from the $result variable in addProperty method.
Solution 1
Create a procedure which will insert the record and return the id of the inserted record.
Solution 2
Create a procedure which will insert all the data to the respective tables and return success or failure.

how to add multi captcha in same page and check both checkbox its fill

I have two forms on a single page, one of them is a login form and the other is a register form (two tabs) and I want to check the the captchas, but when I click the check captcha from register form I can't login.
The login form:
HTML:
<div id="loginUserTab" class="tab-pane fade">
<form>
<div class="form-group login-width-100">
<label for="id_number" class="m-rtl-label"><span class="requiredMark">*</span>passport number:</label>
<input type="text" class="form-control" id="pNo" name="pNo" data-validetta="required,minLength[10],maxLength[10]" lang="fa" style="text-align: left;">
</div>
<div class="form-group login-width-100">
<label for="mNumber" class="m-rtl-label"><span class="requiredMark"></span> telephone :</label>
<input type="text" class="form-control" id="tNumber" name="tNumber" data-validetta="required,minLength[11],maxLength[11]" lang="fa" style="text-align: left;">
</div>
<div class="form-group" style="float:right;padding-right: 20px;">
<div class="g-recaptcha" data-sitekey="...."></div>
</div>
<div class="form-group login-width-100">
<button type="submit" class="btn btn-primary colorGreenBTN">login</button>
</div>
</form>
</div>
JS:
var v = grecaptcha.getResponse();
if (v.length == 0) {
alert("fill the form");
return;
} else if (!$("#Terms").prop("checked")) {
alert("check the rules");
}
Simplest Way to validate as much g-captcha validate
Hope you have included api.js before </head> tag as per below
<script src="https://www.google.com/recaptcha/api.js?onload=CaptchaCallback&render=explicit"></script>
Your HTML Code looks like below
<div class="g-recaptcha-contact" data-sitekey="Your Site Key" id="RecaptchaField2"></div>
<input type="hidden" class="hiddenRecaptcha" name="ct_hiddenRecaptcha" id="ct_hiddenRecaptcha">
<div class="g-recaptcha-quote" data-sitekey="Your Site Key" id="RecaptchaField1"></div>
<input type="hidden" class="hiddenRecaptcha" name="qt_hiddenRecaptcha" id="qt_hiddenRecaptcha">
After you add this code in footer with tag
var CaptchaCallback = function() {
var widgetId1;
var widgetId2;
widgetId1 = grecaptcha.render('RecaptchaField1', {'sitekey' : 'Your Site Key', 'callback' : correctCaptcha_quote});
widgetId2 = grecaptcha.render('RecaptchaField2', {'sitekey' : 'Your Site Key', 'callback' : correctCaptcha_contact});
};
var correctCaptcha_quote = function(response) {
$("#qt_hiddenRecaptcha").val(response);
};
var correctCaptcha_contact = function(response) {
$("#ct_hiddenRecaptcha").val(response);
};
And Last easy step for developer add Jquery Validation as per below
$("#form_id").validate({
ignore: [],
rules: {
ct_hiddenRecaptcha: { required: true, },
qt_hiddenRecaptcha: { required: true, },
},
});
If you have same class for both the forms, you can use it to validate above.

AJAX call PHP same page and reload option values

i have an html form with a date input and a multiselect.
When loading page I load the options of the multiselect through a php function.
What i want to do is to capture onChange event of the date input with a js script and launch the php script to reload the option values of the select using the new date.
This is the php code
<?php
//DEFINE
$dateMinimumInput = "";
// Handle AJAX request for changing DateMinimumInput(start)
if(isset($_POST['ajax']) && isset($_POST["dateMinimumChanged"]) ){
echo "Inside function dateMinimumChanged: " .$_POST['dateMinimumChanged'];
$dateMinimumInput = verify_input($_POST['dateMinimumChanged']);
}
$stationList = selectStations($dateMinimumInput); ?>
This is the javascript
<script>
$(document).ready(function(){
$("#dateMinimumInput").change(function(){
//Selected value
inputValue = $(this).val();
console.log(inputValue);
$.ajax({
type: 'POST',
url: '',
data: {ajax: 1, dateMinimumChanged: inputValue},
success: function(data){
console.log('works');
console.log(data);
$('body').append(response);
},
error: function(){
alert('something went wrong');
}
});
});
});
</script>
and this is the html form
<form class="" role="form" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
<div class="row">
<div class="col-md-6">
<div class="form-group form-row">
<label for="dateMinimumInput" class="col-form-label col-sm-4">Date Minimum:</label>
<div class="col-sm-8">
<div class="form-group">
<input type="date" class="form-control <?php if ( $dateMinimumInputErr !== "") { echo 'is-invalid'; }?>" id="dateMinimumInput" name="dateMinimumInput" placeholder="Enter date minimum" value="<?php echo $dateMinimumInput;?>">
<div class="invalid-feedback"> <?php if ( $dateMinimumInputErr !== "") { echo 'Please, ' .$dateMinimumInputErr; } ?> </div>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group form-row">
<label for="stationInput" class="col-form-label col-sm-4">Station:</label>
<div class="col-sm-8">
<select id="stationInput" name="stationInput[]" class="form-control" multiple>
<?php
foreach($stationList as $station){
if($station['numberofmeasurements'] == 0){
echo '<option disabled="true" value="'.$station['id'] .'">'.$station['location'] .' (' .$station['numberofmeasurements'] .') </option>';
}else{
echo '<option value="'.$station['id'] .'">'.$station['location'] .' (' .$station['numberofmeasurements'] .') </option>';
}
}
?>
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12 text-right">
<button id="submit" name="submit" type="submit" class="btn btn-primary">Search</button>
</div>
</div>
</form>
The fragments of code are all from the same page.
The problem is that when I change the date, the javascript captures the event but the PHP script is not executed and the options are not reload.
Any help about what I'm doing wrong?
Thank you

How to specify minlength in jquery?

If the status value is completed then comment field is required is working good.But the problem is, I want to specify comment field is required for minimum of 50 character.
The Below code: index.php
<!-- Select Basic -->
<div class="form-group">
<label class="col-md-4 control-label" for="selectbasic">Status</label>
<div class="col-md-4">
<select id="status" name="status[]" class="form-control" >
<option value="Pending">Pending</option>
<option value="Work in process">Work in process</option>
<option value="Completed">Completed</option>
</select>
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="textinput">Comment</label>
<div class="col-md-4">
<input id="commentss" name="comment[]" type="text" placeholder="" class="form-control input-md" />
</div>
</div>
<div class="col-md-8 col-sm-12 col-24">
<div class="input_fields" style="color:black">
<button class="add_field btn " onclick="incrementValue()" >Add More</button>
<div>
<input type="text" name="mytextt[]" hidden="" ></div>
</div>
</div>
Javascript
<script type="text/javascript">
$(document).ready(function () {
$("#status").click(function () {
if ($("#status").val() == "Completed") {
$("#commentss").attr("required", "required");
}
else
$("#commentss").attr("required", false);
});
});
</script>
Use length to find the length of the string
if($('#commentss').val().length < 50){
alert("Please enter 50 characters atleast");
} else {
//submit
}
For this please use below code :
<script type="text/javascript">
$(document).ready(function () {
$("#status").click(function () {
var commenttext = document.getElementById('commentss').value;
if (commenttext.length < 50)
{
alert("Please Enter minimum 50 character!")
}
else
{
//Add code
}
});
});
</script>
In Jquery ...
For Dynamic Tracking ...
(You can use blur or keyup even too.)
$(function() {
//disable submit if you want to
$('#commentss').on('input', function(e) {
if(this.value.length >= 50) {
//success
} else {
//fail?
}
});
});
To Validate on Click only ...
Go with the answer of Thamaraiselvam.

ajax form is not working how it should

hello i been working on a form using ajax but when it comes down to validating a select box
problem 1) every time i leave the job_est value empty the form is still submitted as if it was validated
problem 2) can i use async in ajax
sorry for my writing skills
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(document).ready(function() {
//if submit button is clicked
$('#submit').click(function () {
//Get the data from all the fields
var name = $('input[name=name]');
var l_name = $('input[name=l_name]');
var phone = $('input[name=phone]');
var email = $('input[name=email]');
var postcode = $('input[name=postcode]');
var house_number = $('input[name=house_number]');
var street = $('input[name=street]');
var job_est = $('select[name=job_est]');
var comment = $('textarea[name=comment]');
//Simple validation to make sure user entered something
//If error found, add hightlight class to the text field
if (name.val()=='') {
name.addClass('hightlight');
return false;
} else name.removeClass('hightlight');
if (l_name.val()=='') {
l_name.addClass('hightlight');
return false;
} else l_name.removeClass('hightlight');
if (phone.val()=='') {
phone.addClass('hightlight');
return false;
} else phone.removeClass('hightlight');
if (email.val()=='') {
email.addClass('hightlight');
return false;
} else email.removeClass('hightlight');
if (postcode.val()=='') {
postcode.addClass('hightlight');
return false;
} else postcode.removeClass('hightlight');
if (house_number.val()=='') {
house_number.addClass('hightlight');
return false;
} else house_number.removeClass('hightlight');
if (street.val()=='') {
street.addClass('hightlight');
return false;
} else street.removeClass('hightlight');
if (job_est.val()=='') {
job_est.addClass('hightlight');
return false;
} else job_est.removeClass('hightlight');
if (comment.val()=='') {
comment.addClass('hightlight');
return false;
} else comment.removeClass('hightlight');
//organize the data properly
var data = 'name=' + name.val() + '&email=' + email.val() + '&phone=' +
phone.val() + '&comment=' + encodeURIComponent(comment.val());
//disabled all the text fields
$('.text').attr('disabled','true');
//show the loading sign
$('.loading').show();
//start the ajax
$.ajax({
//this is the php file that processes the data and send mail
url: "process.php",
//GET method is used
type: "GET",
//pass the data
data: data,
//Do not cache the page
cache: false,
//success
success: function (html) {
//if process.php returned 1/true (send mail success)
if (html==1) {
//hide the form
$('.form').fadeOut('slow');
//show the success message
$('.done').fadeIn('slow');
//if process.php returned 0/false (send mail failed)
} else alert('Sorry, unexpected error. Please try again later.');
}
});
//cancel the submit button default behaviours
return false;
});
});
</script>
<body>
<div class="block">
<div class="done">
<b>Thank you !</b> We have received your message.
</div>
<div class="form">
<form method="post" action="process.php">
<h4><u>Basic Contact Details</u></h4>
<div style="display: inline-block;" class="element">
<label>Name</label><input type="text" name="name"/>
</div>
<div style="display: inline-block;" class="element">
<label>Last Name: </label><input type="text" name="l_name"/>
</div>
<div class="element">
<label>Phone Number</label>
<input type="text" name="phone"/>
</div>
<div class="element">
<label>Email</label>
<input type="text" name="email"/>
</div>
<div style="display: inline-block;" class="element">
<label>Postcode: </label><input type="text" name="postcode" size="10" maxlength="10">
</div>
<div style="display: inline-block;" class="element">
<label>House Number: </label><input type="text" name="house_number" size="3">
</div>
<div style="display: inline-block;" class="element">
<label>Street Name: </label><input type="text" name="street">
</div>
<div style="display: inline-block;" class="element">
<label>County:</label>
<select>
<option name="select">--SELECT--</option>
<option name="bedford">Bedford</option>
<option name="dunstable">Dunstable</option>
<option name="luton">Luton</option>
</select>
</div>
<h4><u>Job Details</u></h4>
<div class="element">
<label>You Would Like To Book A:</label>
<select name="job_est">
<option name="select">--SELECT--</options>
<option name="job">Job</option>
<option name="est">Estimation</option>
</select>
</div>
<br/>
<div class="element">
<label>Service Your Booking:</label>
<select>
<option name="select">--SELECT--</option>
<option name="gardening">Gardening</option>
<option name="landscaping">Landscaping</option>
<option name="painting">Painting & Decorating</option>
<option name="decking">Decking & Fencing</option>
</select>
</div>
<br/>
<div class="element">
<label>Any Additional Information </label>
<textarea name="comment" class="text textarea" /></textarea>
</div>
<div class="element">
<input type="submit" id="submit"/>
<div class="loading"></div>
</div>
</form>
</div>
</div>
<div class="clear"></div>
You should change selectbox's name attribute with value
<select name="job_est">
<option value="select">--SELECT--</options>
<option value="job">Job</option>
<option value="est">Estimation</option>
</select>
and in your javascript, it should be
if (job_est.val() == 'select') {
job_est.addClass('hightlight');
return false;
}

Categories

Resources