Why the validation error messages don't display - php

I was about to update my existing data in sql.
I am updating the data using ajax with validation error
ajax validation works on my account creation and change password
below are my ajax code
$('#form-battery-update').submit(function(e) {
e.preventDefault();
var me = $(this);
// perform ajax
$.ajax({
// url: me.attr('action'),
url: '<?php echo base_url(); ?>msasset/update_battery_form_validation',
type: 'post',
data: me.serialize(),
dataType: 'json',
success: function(response) {
if (response.success == true) {
// if success we would show message
// and also remove the error class
$('#the-message').append('<div class="alert alert-success">' +
'<span class="glyphicon glyphicon-ok"></span>' +
' UPS Battery has been created' +
'</div>');
$('.form-group').removeClass('has-error')
.removeClass('has-success');
$('.text-danger').remove();
// reset the form
me[0].reset();
// close the message after seconds
$('.alert-success').delay(500).show(10, function() {
$(this).delay(3000).hide(10, function() {
$(this).remove();
});
})
}
else {
$.each(response.messages, function(key, value) {
var element = $('#' + key);
element.closest('div.form-group')
.removeClass('has-error')
.addClass(value.length > 0 ? 'has-error' : 'has-success')
.find('.text-danger')
.remove();
element.after(value);
});
}
}
});
});
below are my code from my views folder
<div class="card-body p-0">
<?php echo form_open("msasset/update_battery_form_validation", array("id" => "form-battery-update", "class" => "form-horizontal")) ?>
<div class="row">
<div class="col-lg-5 d-none d-lg-block bg-register-image"></div>
<div class="col-lg-7">
<div class="p-5">
<div class="text-center">
<h1 class="h4 text-gray-900 mb-4"><?php echo $title; ?></h1>
<div id="the-message"></div>
</div>
<?php
if(isset($fetch_single_battery))
{
foreach($fetch_single_battery->result() as $row)
{
?>
<div class="form-group">
<label>Battery SerialNumber</label> </br>
<p class="form-control"> <?php echo $row->SerialNumber; ?></p>
</div>
<div class="form-group">
<label>PO Number</label> </br>
<input type="text" name="PONumber" value="<?php echo $row->PONumber; ?>" class="form-control"/>
</div>
<div class="form-group">
</div>
<div class="form-group">
<label>Ticket</label>
<input type="text" name="ticketid" value="<?php echo $row->TicketNumber; ?>" class="form-control" />
<span class="text-danger"><?php echo form_error("ticketid"); ?></span>
</div>
<div class="form-group">
</div>
<div class="form-group">
<label>Data Port</label>
<select class="form-control" name="select_port">
<option class="form-control" selected><?php echo $row->DataPort; ?></option>
<?php foreach ($GetPortLocation as $Port) { ?>
<option value="<?php echo $Port['DataPort']; ?>"><?php echo $Port['DataPort']; ?></option>
<?php } ?>
</select>
<span class="text-danger"><?php echo form_error("select_port"); ?></span>
<span class="text-danger"></span>
</div>
<div class="form-group">
<label>UPS Asset Tag</label>
<input type="text" name="ups_asset_tag" value="<?php echo $row->UPS_AssetTag; ?>" class="form-control" />
<span class="text-danger"></span>
</div>
<div class="form-group">
<label>Date Installed</label>
<input type="date" name="date_installed" value="<?php echo $row->DateInstalled; ?>" class="form-control" />
<span class="text-danger"></span>
</div>
<div class="form-group">
<label>Status</label>
<select class="form-control" name="select_status">
<option class="form-control" selected><?php echo $row->Status; ?></option>
<?php foreach($get_AssetStatus as $AssetStatus){?>
<option value="<?php echo $AssetStatus['AssetStatus']; ?>"><?php echo $AssetStatus['AssetStatus']; ?></option>
<?php } ?>
</select>
</div>
<div class="form-group">
<input type="hidden" name="hidden_id" value="<?php echo $row->ID; ?>" />
<input type="submit" name="update" id="update" value="Update" class="btn btn-info" />
<input type="submit" name="insert" id="insert" value="Update" class="btn btn-primary">
</div>
<?php
}
}
?>
</form>
</div>
</div>
</div>
</div>
below codes from my controller
function update_battery_form_validation()
{
$data = array('success' => false, 'messages' => array());
$this->load->library('form_validation');
$this->form_validation->set_rules('PONumber','po number','required');
// $this->form_validation->set_rules('ticketid','ticket id','required');
if($this->form_validation->run() == TRUE)
{
$this->load->model('assets_model');
$data = array(
'PONumber' => $this->input->post('PONumber'),
'TicketNumber' => $this->input->post('ticketid'),
'DataPort' => $this->input->post('select_port'),
'UPS_AssetTag' => $this->input->post('ups_asset_tag'),
'DateInstalled' => $this->input->post('date_installed'),
'Status' => $this->input->post('select_status'),
'PerformedBy' => $this->session->userdata('user_name')
);
if($this->input->post('update'))
{
$this->assets_model->update_battery($data,$this->input->post('hidden_id'));
$this->session->set_flashdata('batteries_updated','New battery has been updated successfully');
redirect('msasset/ups_batteries');
}
}
else
{
// echo validation_errors();
foreach ($_POST as $key => $value)
{
$data['messages'][$key] = form_error($key);
}
}
echo json_encode($data);
}
I was expecting that every time there is an empty fields it should give me an a this fields required messages and also if all the fields fill with data it also does not load the page or save the data

Related

show select checkbox looping from ajax and codeigniter

i want to show checkbox looping from db, if i try to select data id_kendaraan in field then show the data from that id.
this my view code:
<div class="modal fade" id="tambah" tabindex="-1" role="dialog" aria-labelledby="largeModal" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">x</button>
<h3 class="modal-title" id="myModalLabel">Tambah Pemeliharaan</h3>
</div>
<form class="form-horizontal" method="post" action="<?php echo base_url()?>Data/Pemeliharaan/Tambah">
<div class="modal-body">
<div class="form-group">
<label class="control-label col-xs-3">Nama Kendaraan</label>
<div class="col-xs-8">
<select class="form-control" name="id_kendaraan" id="id_kendaraan" required>
<option>Pilih Kendaraan</option>
<?php
if(!empty($kendaraan_)) {
foreach ($kendaraan_ as $isi) {
?>
<option value="<?php echo $isi['id_kendaraan']?>"><?php echo $isi['nama']?> - <?php echo $isi['platno']?></option>
<?php }} ?>
</select>
</div>
</div>
<?php
$index =0;
foreach ($subkriteria_ as $kr_key => $kriteria) {
?>
<div class="form-group">
<label class="control-label col-xs-3"><?php echo $kriteria['nama_kriteria'] ?></label>
<div class="col-xs-8">
<input type="hidden" name="status_pemeliharaan" value="1" class="form-control">
<input type="hidden" name="id_kriteria[]" value="<?php echo $kriteria['id_kriteria'] ?>" class="form-control">
<?php if(!empty($kriteria['sub'])) { ?>
<select class="form-control" name="isi_kriteria[]" required>
<option>Pilih Sub Kriteria</option>
<?php $no = 1; foreach ($kriteria['sub'] as $data) { ?>
<option value="<?php echo $data['value'] ?>"><?php echo $data['namasubkriteria'] ?> - <?php echo $data['value'] ?></option>
<?php $no++; } ?>
</select>
<?php } else if($kriteria['link']=='tahun_beli') { ?>
<input name="isi_kriteria[]" value="" class="form-control" type="text" placeholder="Isi Kriteria..." readonly required>
<?php } else { ?>
<input name="isi_kriteria[]" value="" class="form-control" type="number" placeholder="Isi Kriteria..." required>
<?php } ?>
</div>
</div>
<?php } ?>
<div class="form-group">
<label class="control-label col-xs-3">tes</label>
<div class="col-xs-8">
<input type="checkbox" name="id_sparepart[]" value=""> //my trouble
<input type="text" name="sparepart" value=""> //my trouble
</div>
</div>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">Tutup</button>
<button class="btn btn-info">Submit</button>
</div>
</form>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){
$('#id_kendaraan').on('input',function(){
var id_kendaraan=$(this).val();
$.ajax({
type : "POST",
url : "<?php echo base_url('Data/Pemeliharaan/GetKendaraanById')?>",
dataType : "JSON",
data : {id_kendaraan: id_kendaraan},
cache:false,
success: function(data){
$.each(data,function(id_kendaraan, tahun_beli, jenis){
$('[name="isi_kriteria[]"]').val(data.tahun_beli);
$('[name="id_jenis"]').val(data.id_jenis);
$('[name="id_sparepart[]"]').val(data.id_sparepart); //my trouble
$('[name="sparepart"]').val(data.sparepart); //my trouble
});
}
});
return false;
});
});
</script>
on this code, if I select a kendaraan from the select form then data appears according to the selected kendaraan.
it is working, but on the checkbox not show data sparepart for looping from database.
this my controller:
function GetKendaraanById(){
$id_kendaraan=$this->input->post('id_kendaraan');
$data=$this->PemeliharaanModel->GetById($id_kendaraan); ;
echo json_encode($data);
}
i get data from view $id_kendaraan for my parameter.
this my model:
function GetById($id_kendaraan){
$this->db->select('*');
$this->db->from('tb_kendaraan');
$this->db->join('tb_sparepart', 'tb_sparepart.id_jenis = tb_kendaraan.id_jenis');
$this->db->where('tb_kendaraan.id_kendaraan',$id_kendaraan);
$query = $this->db->get();
if($query->num_rows() > 0)
{
foreach ($query->result() as $data) {
$hasil=array(
'tahun_beli' => $data->tahun_beli,
'id_jenis' => $data->id_jenis,
'id_sparepart' => $data->id_sparepart,
'sparepart' => $data->sparepart,
);
}
}
return $hasil;
}
field tahun_beli, id jenis is success to showing in the view.
but the checkbox from sparepart is not looping just show one data.
after selecting the nama kendaraan the checkbox should appear according to the type of kendaraan, data circled in the image should appear more checkbox
thx for helping me
You should separate the query on your model because it has a different format to show (I assume you want to get one kendaraan data with multiple sparepart data) :
function GetById($id_kendaraan){
$this->db->select('*');
$this->db->from('tb_kendaraan');
$this->db->where('tb_kendaraan.id_kendaraan',$id_kendaraan);
$query_kendaraan = $this->db->get();
$hasil = false;
if($query_kendaraan->num_rows() > 0)
{
$data_kendaraan = $query_kendaraan->row();
$hasil = [
'tahun_beli' => $data_kendaraan->tahun_beli,
'id_jenis' => $data_kendaraan->id_jenis,
'spareparts' => [] // empty array, to be filled with spareparts data
];
$this->db->select('*');
$this->db->from('tb_sparepart');
$this->db->where('tb_sparepart.id_jenis', $data_kendaraan->id_jenis);
$query_sparepart = $this->db->get();
foreach ($query_sparepart->result() as $data_sparepart) {
$spareparts = [
'id_sparepart' => $data_sparepart->id_sparepart,
'sparepart' => $data_sparepart->sparepart,
];
array_push($hasil['spareparts'], $spareparts);
}
}
return $hasil;
}
Then on the html side, try to modify the codes like this :
<div class="modal fade" id="tambah" tabindex="-1" role="dialog" aria-labelledby="largeModal" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">x</button>
<h3 class="modal-title" id="myModalLabel">Tambah Pemeliharaan</h3>
</div>
<form class="form-horizontal" method="post" action="<?php echo base_url()?>Data/Pemeliharaan/Tambah">
<div class="modal-body">
<div class="form-group">
<label class="control-label col-xs-3">Nama Kendaraan</label>
<div class="col-xs-8">
<select class="form-control" name="id_kendaraan" id="id_kendaraan" required>
<option>Pilih Kendaraan</option>
<?php
if(!empty($kendaraan_)) {
foreach ($kendaraan_ as $isi) {
?>
<option value="<?php echo $isi['id_kendaraan']?>"><?php echo $isi['nama']?> - <?php echo $isi['platno']?></option>
<?php }} ?>
</select>
</div>
</div>
<?php
$index =0;
foreach ($subkriteria_ as $kr_key => $kriteria) {
?>
<div class="form-group">
<label class="control-label col-xs-3"><?php echo $kriteria['nama_kriteria'] ?></label>
<div class="col-xs-8">
<input type="hidden" name="status_pemeliharaan" value="1" class="form-control">
<input type="hidden" name="id_kriteria[]" value="<?php echo $kriteria['id_kriteria'] ?>" class="form-control">
<?php if(!empty($kriteria['sub'])) { ?>
<select class="form-control" name="isi_kriteria[]" required>
<option>Pilih Sub Kriteria</option>
<?php $no = 1; foreach ($kriteria['sub'] as $data) { ?>
<option value="<?php echo $data['value'] ?>"><?php echo $data['namasubkriteria'] ?> - <?php echo $data['value'] ?></option>
<?php $no++; } ?>
</select>
<?php } else if($kriteria['link']=='tahun_beli') { ?>
<input name="isi_kriteria[]" value="" class="form-control" type="text" placeholder="Isi Kriteria..." readonly required>
<?php } else { ?>
<input name="isi_kriteria[]" value="" class="form-control" type="number" placeholder="Isi Kriteria..." required>
<?php } ?>
</div>
</div>
<?php } ?>
<div class="form-group">
<label class="control-label col-xs-3">tes</label>
<div class="col-xs-8">
<ul id="sparepartList" style="list-style-type: none; padding: 0;"></ul>
</div>
</div>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">Tutup</button>
<button class="btn btn-info">Submit</button>
</div>
</form>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){
$('#id_kendaraan').on('input',function(){
var id_kendaraan=$(this).val();
$.ajax({
type : "POST",
url : "<?php echo base_url('Data/Pemeliharaan/GetKendaraanById')?>",
dataType : "JSON",
data : {id_kendaraan: id_kendaraan},
cache:false,
success: function(data){
$('#sparepartList').empty(); // clear all sparepart checkboxes
$.each(data, function(id_kendaraan, tahun_beli, jenis){
$('[name="isi_kriteria[]"]').val(data.tahun_beli);
$('[name="id_jenis"]').val(data.id_jenis);
});
$.each(data.spareparts, function (key, value) {
let li = $('<li><input type="checkbox" name="id_sparepart[]" value="' + value.id_sparepart + '" />' +
'<input type="text" name="sparepart" value="' + value.sparepart + '" /></li>');
$('#sparepartList').append(li);
});
}
});
return false;
});
});
</script>
Notice that I changed the sparepart html inputs to an unordered list element, then loop the sparepart data retrieved from the ajax response inside it.
in Your model
$hasil=array(
'tahun_beli' => $data->tahun_beli,
'id_jenis' => $data->id_jenis,
'id_sparepart' => $data->id_sparepart,
'sparepart' => $data->sparepart,
);
U should Store data in $hasil by using []
$hasil[]=array(
'tahun_beli' => $data->tahun_beli,
'id_jenis' => $data->id_jenis,
'id_sparepart' => $data->id_sparepart,
'sparepart' => $data->sparepart,
);

Showing Alert of update successful but not able to click alert, and database not updated

When I click on update, a page is only getting refreshed, values are not updated. I have 4 tables in database, namely -> stud,country_master_academic,master_state, master_city. In a console, values are not showing when I click on update button.
my update.php page
<div class="container" style="width:700px;height:1100px;margin-top:10%;box-shadow:4px 3px 3px 3px grey;margin-left:25%;background-color:#eaf2fa;padding:3%;">
<h4 style="font-weight:bold;"><span class="glyphicon glyphicon-edit"></span>Update Student</h4>
<div class="form-group">
<label for="photo"></label>
<?php
$img = "images/".trim($vrow["photo"]);
echo '<img src='.$img.' id="resultedPhoto" class="image" style="margin-left:75%;margin-top:2%;width:120px;height:120px;border:2px solid #bbbbbb;border-radius:10px;">';
?><br/>
<input type="file" name="upphoto" id="upphoto" style="margin-left:70%;" required />
</div>
<form class="form-horizontal" name="form1" id="form1" method="post" action="<?php $_PHP_SELF?>" enctype="multipart/form-data">
<div class="form-group">
<label for="no"><span class="glyphicon glyphicon-lock"></span><b> Student No: </b></label>
<input type="text" class="form-control" name="upno" id="upno" disabled value="<?php echo $vrow['stud_no'];?>" required />
</div>
<div class="form-group">
<label for="name"><span class="glyphicon glyphicon-user"></span><b> Student Name: </b></label>
<input type="text" class="form-control" name="upname" id="upname" value="<?php echo $vrow['stud_name'];?>" required pattern="[a-zA-Z]{3,}" title="Name should only contain letters and atleast 3 letters"/>
</div>
<div class="form-group">
<label for="no"><span class="glyphicon glyphicon-phone"></span><b> Mobile No: </b></label>
<input type="text" class="form-control" value="<?php echo $vrow['mobile']; ?>" name="upmob_no" required id="upmob_no" pattern="[0-9]{10}" title="Mobile number should be of 10 digits"/>
</div>
<div class="form-group">
<label for="dob"><span class="glyphicon glyphicon-calendar"></span><b> Birth Date: </b></label>
<input type="date" required class="form-control" value="<?php echo $vrow['dob'];?>" name="updob" id="updob" />
</div>
<div class="form-group">
<label for="add"><span class="glyphicon glyphicon-map-marker"></span><b> Address: </b></label>
<textarea rows="4" cols="33" class="form-control" name="upadd" id="upadd" required><?php echo $vrow['address'];?></textarea>
</div>
<div class="form-group">
<label for="gen"><b> Gender: </b></label>
<input type="radio" name="gender" id="genderMale" value="M"<?php echo ($vrow['gender']=='M')?'checked':' ' ?> required="required">Male
<input type="radio" name="gender" id="genderFemale" value="F"<?php echo ($vrow['gender']=='F')?'checked':' ' ?> required="required">Female
</div>
<div class="form-group">
<label for="cntry"><span class="glyphicon glyphicon-map-marker"></span><b> Country: </b></label>
<select required name="upcountry" id="upcountry" class="form-control">
<option value="">Select</option>
<?php
$country="SELECT * from country_master_academic";
$res= $conn->query($country);
if($res->num_rows>0){
while($row=$res->fetch_assoc()){
if($row["country_name"]==$vcountry or $vrow['country'] == $row["country_code"] )
{
echo '<option value='.$row["country_code"].' selected>'.$row["country_name"].'</option>';
}
else
{
echo '<option value='.$row["country_code"].'>'.$row["country_name"].'</option>';
}
}
}
?>
</select>
</div>
<div class="form-group">
<label for="state"><span class="glyphicon glyphicon-map-marker"></span><b> State: </b></label>
<select required name="upstate" id="upstate" class="form-control">
<option value="">Select</option>
<?php
$state="SELECT * from master_state";
$res= $conn->query($state);
if($res->num_rows>0){
while($row=$res->fetch_assoc()){
if($row["state_name"]==$vstate or $vrow['state'] == $row["state_code"] )
{
echo '<option value='.$row["state_code"].' selected>'.$row["state_name"].'</option>';
}
else
{
echo '<option value='.$row["state_code"].'>'.$row["state_name"].'</option>';
}
}
}
?>
</select>
</div>
<div class="form-group">
<label for="city"><span class="glyphicon glyphicon-map-marker"></span><b> City: </b></label>
<select required name="upcity" id="upcity" class="form-control">
<option value="">Select</option>
<?php
$city="SELECT * from master_city";
$res= $conn->query($city);
if($res->num_rows>0){
while($row=$res->fetch_assoc()){
if($row["city_name"]==$vcity or $vrow['city'] == $row["city_code"] )
{
echo '<option value='.$row["city_code"].' selected>'.$row["city_name"].'</option>';
}
else
{
echo '<option value='.$row["city_code"].'>'.$row["city_name"].'</option>';
}
}
}
?>
</select>
</div>
<br/>
<div class="form-group">
<button type="submit" name="update" id="update" style="font-weight:bold;" class="btn btn-primary">Update</button>
</div>
</form>
</div>
upresult.php page
<?php
include("connection.php");
$no=trim($_POST['upno']);
$name=trim($_POST['upname']);
$mob=trim($_POST['upmob_no']);
$dob=trim($_POST['updob']);
$add=trim($_POST['upadd']);
$photo=trim($_FILES['upphoto']['name']);
$gen=trim($_POST['gender']);
$cn=trim($_POST['upcountry']);
$st=trim($_POST['upstate']);
$ct=trim($_POST['upcity']);
$qry="update stud set stud_name='".$name."',mobile='".$mob."',dob='".$dob."',address='".$add."',gender='".$gen."',country='".$cn."',state='".$st."',city='".$ct."' where stud_no='".$no."'";
$data=mysqli_query($conn,$qry);
if($data)
{
echo '<script language="javascript">';
echo 'alert("Updated Successfully")';
echo '</script>';
}
else {
echo '<script language="javascript">';
echo 'alert("Cannot update record")';
echo '</script>';
}
?>
jquery
$(document).ready(function(){
$("#form1").submit(function(event){
event.preventDefault();
var formData = new FormData(this);
$.ajax({
url:"upresult.php",
type:"POST",
data:{formData:formData},
async:true,
success:function(data) {
alert(data);
},
cache:false,
contentType:false,
processData:false
});
});
});
Thank you in advance.
Don't use the same name
data:{stud_no:stud_no}, //here change the name of vbl or value
data:{
formData:formData, //here change the name of vbl or value
stud_no:stud_no, //here change the name of vbl or value
}

Internal Server Error while doing an insertion in Codeigniter

I am working on a simple CRUD application using Codeigniter, and this section of code was working perfectly well until I added more functions.
Here is the problem:
I was adding 3 items to the database from user inputs, and it had no error. But when I added more input fields to get more inputs from the user, I ended up getting an Internal Server Error when I click on the "Add Item" button.
Below is the View Code:
<?php
if ($_SESSION[AppStrings::$NOMENCLATURE] != AppStrings::$SERVICE) {
if ($_SESSION[AppStrings::$SIZE] != AppStrings::$MICRO) {
?>
<form data-toggle="validator" class="form-horizontal form-material" method="post" action="#" onsubmit="addProduct(); return false;">
<div class="form-group m-t-40">
<div class="col-xs-12">
<div class="input-group">
<div class="input-group-addon"><i class="mdi mdi-barcode-scan"></i></div>
<input class="form-control" type="text" required="" placeholder=" <?= $nomenclature ?> Code" id="product_code" required/>
</div>
</div>
</div>
<div class="form-group m-t-40">
<div class="col-md-6">
<input class="form-control" type="text" required="" placeholder="<?= $nomenclature ?> Name" id="product_name" required/>
</div>
<div class="col-md-6">
<div class="input-group">
<div class="input-group-addon"><i class="mdi mdi-currency-ngn"></i></div>
<input class="form-control" type="number" required="" placeholder=" <?= $nomenclature ?> Cost Price" name="product_cp" id="product_cp" required/>
</div>
</div>
</div>
<div class="form-group m-t-40">
<div class="col-md-6">
<div class="input-group">
<div class="input-group-addon"><i class="mdi mdi-currency-ngn"></i></div>
<input class="form-control" type="number" required="" placeholder=" <?= $nomenclature ?> Selling Price" name="product_sp" id="product_sp" required/>
</div>
</div>
</div>
<div class="form-group m-t-40">
<div class="col-md-6">
<textarea class="form-control" type="text" required="" placeholder=" <?= $nomenclature ?> Description" id="product_des" required/></textarea>
</div>
<div class="col-md-6">
<input class="form-control" type="text" required="" placeholder=" <?= $nomenclature ?> Expiry Date" id="product_exp" onfocus="(this.type = 'date')" onblur="if (this.value == '') {
this.type = 'text'
}" required/>
</div>
</div>
<div class="form-group m-t-40">
<div class="col-md-6">
<div class="input-group">
<div class="input-group-addon"><i class="mdi mdi-clipboard-account"></i></div>
<select name="supplier" class="form-control form-control-line" type="text" id="supplier" placeholder="<?= $nomenclature ?> Supplier">
<option value="">Supplier</option>
<?php
foreach ($suppliers as $supplier) {
?>
<option value='<?= $supplier[DbStrings::$SUPPLIER_NAME] ?>'><?= $supplier[DbStrings::$SUPPLIER_NAME] ?></option>
<?php
}
?>
</select>
</div>
</div>
<div class="col-md-6">
<div class="input-group">
<div class="input-group-addon"><i class="mdi mdi-chevron-double-up"></i></div>
<select name="department" class="form-control form-control-line" type="text" id="department" placeholder="<?= $nomenclature ?> Department">
<option value="">Department</option>
<?php
foreach ($departments as $department) {
?>
<option value='<?= $department[DbStrings::$DEPARTMENT_NAME] ?>'><?= $department[DbStrings::$DEPARTMENT_NAME] ?></option>
<?php
}
?>
</select>
</div>
</div>
</div>
<div class="form-group m-t-40">
<div class="col-md-6">
<div class="input-group">
<div class="input-group-addon"><i class="mdi mdi-chevron-up"></i></div>
<select name="sub_departments" class="form-control form-control-line" type="text" id="sub_department" placeholder="<?= $nomenclature ?> Department">
<option value="">Sub-Department</option>
<?php
foreach ($sub_departments as $sub_department) {
?>
<option value='<?= $sub_department[DbStrings::$SUB_DEPARTMENT_NAME] ?>'><?= $sub_department[DbStrings::$SUB_DEPARTMENT_NAME] ?></option>
<?php
}
?>
</select>
</div>
</div>
<div class="col-md-6">
<div class="input-group">
<div class="input-group-addon"><i class="mdi mdi-cash"></i></div>
<input class="form-control" type="number" placeholder=" <?= $nomenclature ?> Vat" id="vat"/>
</div>
</div>
</div>
<div class="form-group text-center m-t-20">
<div class="col-xs-12">
<button class="btn btn-primary btn-login btn-lg btn-block text-uppercase waves-effect waves-light" type="submit" name="product-btn">Add <?= $nomenclature ?></button>
</div>
</div>
</div> <!-- added in the edit -->
</div> <!-- added in the edit -->
</form>
<?php
}
}
?>
Here is the AJAX code:
function addProduct() {
var product_code = $("#product_code").val();
var product_name = $("#product_name").val();
var product_cp = $("#product_cp").val();
var product_sp = $("#product_sp").val();
var product_des = $("#product_des").val();
var product_exp = $("#product_exp").val();
var supplier = $("#supplier").val();
var department = $("#department").val();
var sub_department = $("#sub_department").val();
var vat = $("#vat").val();
var addUrl = "home/addproduct";
addUrl += "/" + product_code;
addUrl += "/" + product_name;
addUrl += "/" + product_cp;
addUrl += "/" + product_sp;
addUrl += "/" + product_des;
addUrl += "/" + product_exp;
addUrl += "/" + supplier;
addUrl += "/" + department;
addUrl += "/" + sub_department;
addUrl += "/" + vat;
$.ajax({type: 'GET', url: addUrl, data: {},
success: function (result) {
$.alert({
content: result
});
$("#product_code").val("");
$("#product_name").val("");
$("#product_cp").val("");
$("#product_sp").val("");
$("#product_des").val("");
$("#product_exp").val("");
$("#supplier").val("");
$("#department").val("");
$("#sub_department").val("");
$("#vat").val("");
location.reload();
},
error: function (xhr, status, error) {
$.alert({
content: 'Could not complete the process. ' + error
});
}
});
}
Here is the Controller Function:
private function addproduct($product_code = null, $product_name = null, $product_cp = null, $product_sp = null, $product_des = null, $product_exp = null, $supplier = null, $department = null, $sub_department = null, $vat = null) {
if (isset($product_code, $product_name, $product_cp, $product_sp, $product_des, $product_exp, $supplier, $department, $sub_department, $vat)) {
$email = $_SESSION[DbStrings::$EMAIL];
$product_code = $this->test_input($product_code);
$product_name = $this->test_input($product_name);
$product_cp = $this->test_input($product_cp);
$product_sp = $this->test_input($product_sp);
$product_des = $this->test_input($product_des);
$supplier = $this->test_input($supplier);
$department = $this->test_input($department);
$sub_department = $this->test_input($sub_department);
$vat = $this->test_input($vat);
$product_exp = strtotime($product_exp);
$insertedProduct = $this->member->insertProduct($email, $product_code, $product_name, $product_cp, $product_sp, $product_des, $supplier, $department, $sub_department, $vat, $product_exp);
if ($insertedProduct) {
echo "Your " . $_SESSION[AppStrings::$NOMENCLATURE] . " has been added succesfully";
} else {
echo "There was a problem inserting your " . $_SESSION[AppStrings::$NOMENCLATURE] . ". Please try again.";
}
} else {
echo 'Please fill all fields';
}
}
And this is the Model that does the insertion before sending back a result:
public function insertProduct($email, $product_code, $product_name, $product_cp, $product_sp, $product_des, $supplier, $department, $sub_department, $vat, $product_exp) {
$data = array(
DbStrings::$PRODUCTID => "",
DbStrings::$EMAIL => $email,
DbStrings::$PRODUCT_CODE => $product_code,
DbStrings::$PRODUCT_NAME => $product_name,
DbStrings::$PRODUCT_COST => $product_cp,
DbStrings::$PRODUCT_SELLING => $product_sp,
DbStrings::$PRODUCT_MARKUP => 9,
DbStrings::$PRODUCT_DESCRIPTION => $product_des,
DbStrings::$SUPPLIER => $supplier,
DbStrings::$DEPARTMENT => $department,
DbStrings::$SUB_DEPARTMENT => $sub_department,
DbStrings::$VAT => $vat,
DbStrings::$STOCK_BALANCE => 1,
DbStrings::$MIN_LEVEL => 1,
DbStrings::$MAX_QUANTITY => 1,
DbStrings::$QUANTITY_SOLD => 1,
DbStrings::$EXPIRY_DATE => $product_exp,
DbStrings::$DATE_CREATED => time(),
DbStrings::$DATE_STOCKED => time()
);
return $this->db->insert(DbStrings::$PRODUCTS_TABLE_NAME, $data);
}
I still get an error from the server, and don't know what else to do.
Correcting the above issue, the code works fine. I used: $this->output->enable_profiler(TRUE); and i was able to see the MySQL query sent by the model to the server, and when i copied the query and pasted it in my localhost:phpmyadmin, i got flagged for errors and there seem to be no syntax error.
Now this is creeping me out, as i can't fix it.

TypeError: 'checkValidity' called on an object that does not implement interface HTMLTextAreaElement

I am facing this error and the email could not be sent because of this error. I have added a new extension Birthday reminder in opencart v2.0.1.1
I have searched about the error but could not resolve it. Please help. code for the file is this.
<form class="form mailForm">
<div class="row form-group" style="text-align: center; font-size: 18px;">
<div class="col-xs-4">
<div class="brCustomerMailInfo">
<label>To: </label>
<strong><?php if(!empty($customerInfo['email'])) echo $customerInfo['email']; ?></strong>
<input type="hidden" name="customer_id" value="<?php if(!empty($customerInfo['customer_id'])) echo $customerInfo['customer_id']; ?>" />
<input type="hidden" name="to_mail" value="<?php if(!empty($customerInfo['email'])) echo $customerInfo['email'];?>" />
</div>
</div>
<div class="col-xs-4">
<div class="brCustomerMailInfo">
<label>Born:</label>
<strong><?php if(!empty($customerInfo['birthday_date'])){
echo $customerInfo['birthday_date'];
}
?></strong>
</div>
</div>
<div class="col-xs-4">
<div class="brCustomerMailInfo">
<label>Age:</label>
<strong>
<?php if(!empty($customerInfo['birthday_date'])) {;
$now = new DateTime("now");
if (strpos($customerInfo['birthday_date'],'/') !== false) {
echo floor((time()-strtotime(str_replace('/', '-', $customerInfo['birthday_date'])))/(365*60*60*24)) ;
} else {
echo floor((time()-strtotime($customerInfo['birthday_date']))/(365*60*60*24)) ;
}
}?>
</strong>
</div>
</div>
</div>
<div class="row form-group">
<div class="col-xs-3">
<h5><strong><?php echo $discount_code_text ?></strong></h5>
</div>
<div class="col-xs-9">
<strong><?php echo $discount_code?></strong>
<input type="hidden" class="brSmallField form-control" name="discount_code" value="<?php echo $discount_code?>">
</div>
</div>
<div class="row form-group">
<div class="col-xs-3"><h5><strong><span class="required">* </span><?php echo $type_of_discount;?></strong></h5></div>
<div class="col-xs-3">
<select class="form-control" name="discount_type" >
<option value="P"><?php echo $percentage_text?></option>
<option value="F" <?php if(!empty($data['BirthdayReminder']['discount_type']) && $data['BirthdayReminder']['discount_type'] == "F") echo "selected";?>><?php echo $fixed_amount; ?></option>
</select>
</div>
</div>
<div class="row form-group">
<div class="col-xs-3"><h5><strong><span class="required">* </span><?php echo $discount_text;?></strong></h5></div>
<div class="col-xs-3">
<div class="input-group">
<input type="text" class="brSmallField form-control" name="discount" value="<?php if(!empty($data['BirthdayReminder']['discount'])) echo $data['BirthdayReminder']['discount']; ?>">
<span class="input-group-addon" >%</span>
</div>
</div>
</div>
<div class="row form-group">
<div class="col-xs-3"><h5><strong><span class="required">* </span><?php echo $total_amount; ?></strong></h5></div>
<div class="col-xs-3">
<div class="input-group">
<input type="text" class="brSmallField form-control" name="total_amount" value="<?php echo $data['BirthdayReminder']['total_amount'] ?>">
<span class="input-group-addon" ><?php echo $currency ?></span>
</div>
</div>
</div>
<div class="row form-group">
<div class="col-xs-3"><h5><strong><span class="required">* </span>Subject:</strong></h5></div>
<div class="col-xs-3">
<input placeholder="Mail subject" type="text" id="subject" class="form-control" name="subject" value="<?php if(!empty($data['BirthdayReminder']['subject'])) echo $data['BirthdayReminder']['subject']; else echo $default_subject; ?>" />
</div>
</div>
<div class="row form-group">
<div class="col-xs-3"><h5><strong><span class="required">* </span><?php echo $user_email; ?></strong></h5></div>
<div class="col-xs-9">
<textarea class="form-control" id="giftMessage">
<?php if(!empty($customerInfo)) {
$wordTemplates = array("{firstname}", "{lastname}", "{discount_code}");
$words = array($customerInfo['firstname'], $customerInfo['lastname'], $discount_code);
if(!empty($data['BirthdayReminder']['message'][$customerInfo['language_id']])) {
$message = str_replace($wordTemplates, $words,$data['BirthdayReminder']['message'][$customerInfo['language_id']]);
echo $message;
} else {
$default_message = str_replace($wordTemplates, $words, $default_message);
echo $default_message;
}
}?>
</textarea>
</div>
</div>
<div class="row form-group">
<div class="col-xs-4"> </div>
<div class="col-xs-4" style="text-align: center"><button class="btn btn-lg btn-primary" id="sendGift"><?php echo $send_gift_button; ?></button></div>
</div>
</form>
<script>
var gettingOptions = function () {
$('textarea[id="giftMessage"]').each(function(index, element) {
$('#'+element.id).summernote({
height:150
});
$('.btn#sendGift').on('click', function(e){
e.preventDefault();
var currentYear = new Date().getFullYear();
var errorInput = false;
if(!$('input[name="subject"]').val()){
e.preventDefault();
errorInput = true;
$('input[name="subject"]').css({'background':'#f2dede'});
}
if(!validateNumber($('input[name="discount"]'), e)) {
errorInput = true;
}
if(!validateNumber($('input[name="total_amount"]'), e)) {
errorInput = true;
}
if(!errorInput) {
var isSentGift = false;
var lastGift = "<?php if(isset($customerInfo['last_gift_date'])){ $date = explode('-', $customerInfo['last_gift_date']); echo $date[0]; } else { echo '0';}?>";
if(currentYear == lastGift){
isSentGift= true;
}
sentAgain = true;
if(isSentGift) {
var last_gift_date = "<?php if(!empty($customerInfo['last_gift_date'])) {
echo $customerInfo['last_gift_date'];
}
?>";
var sentAgain=confirm("A gift is sent to this customer on " + last_gift_date + ". Do you want to sent this again?");
}
if(sentAgain){
$.ajax({
url: 'index.php?route=<?php echo $modulePath;?>/sendGift&token=' + getURLVar('token') ,
dataType: 'html',
data:{
discount_code: $("input[name='discount_code']").val(),
discount: $("input[name='discount']").val(),
total_amount: $("input[name='total_amount']").val(),
discount_type: $("select[name='discount_type']").val(),
customer_id: $("input[name='customer_id']").val(),
to_mail: $("input[name='to_mail']").val(),
subject: $("input[name='subject']").val(),
gift_message: $('#'+element.id).summernote('code') },
type: 'POST',
dataType:"json",
success: function(data){
$('.messageHasBeenSent').show().delay(3000).fadeOut(600);
$('.btn.btn-link.active').click();
}
});
}
$("#sendEmailModal").modal('hide');
}
else {
e.preventDefault();
}
});
});
};
$("#sendEmailModal").on('shown.bs.modal', function (e) {
gettingOptions();
});
if($('select[name="discount_type"]').val() == 'P'){
$('#percentageAddonForm').show();
} else {
$('#currencyAddonForm').show();
}
$('select[name="discount_type"]').on('change', function(e){
if($(this).val() == 'P') {
$('#percentageAddonForm').show();
$('#currencyAddonForm').hide();
} else {
$('#currencyAddonForm').show();
$('#percentageAddonForm').hide();
}
});
function validateNumber(input, theEvent) {
var regex = /[0-9]|\./;
if(!regex.test(input.val())) {
input.css({'background':'#f2dede'});
return false;
} else {
return true;
}
}
</script>
I have got this resolved!
if(sentAgain){
$.ajax({
url: 'index.php?route=<?php echo $modulePath;?>/sendGift&token=' + getURLVar('token') ,
dataType: 'html',
data:{
discount_code: $("input[name='discount_code']").val(),
discount: $("input[name='discount']").val(),
total_amount: $("input[name='total_amount']").val(),
discount_type: $("select[name='discount_type']").val(),
customer_id: $("input[name='customer_id']").val(),
to_mail: $("input[name='to_mail']").val(),
subject: $("input[name='subject']").val(),
gift_message: $('#'+element.id).summernote('code') },
type: 'POST',
dataType:"json",
success: function(data){
$('.messageHasBeenSent').show().delay(3000).fadeOut(600);
$('.btn.btn-link.active').click();
}
});
}
This is the ajax call and this line was causing the problem
gift_message: $('#'+element.id).summernote('code')
So I change it with this
gift_message: $('#giftMessage').val()
the element was undefined in this case.

JQuery fires upon submitting form

I'm currently creating a page where you can fill in damage claims about damaged cars/goods. You have 3 options (driver/subcontractor/personel) and JQuery is used to show/hide different textboxes according to the selected option.
Here's where it gets tricky. Everything works great until I submit the form. When I do it fires the changeVehicle JQuery-function again and reloads the original value in licensePlate again, even after I altered it in the form. The result being that I get the old variable for my license plate.
Does anyone have an idea why it refires?
My code:
<?php
...
<form id="form" class="form-horizontal" method="post" action="<?php echo $url?>&action=edit<?php echo $edit?>" enctype="multipart/form-data">
<div class="control-group">
<label class="control-label" for="filenr"><?php echo $lng->show("claim_file_nr")?></label>
<div class="controls">
<input type="text" id="filenr" name="filenr" value="<?php echo $file_nr?>" disabled>
<input type="hidden" id="file_nr" name="file_nr" value="<?php echo $file_nr?>" />
</div>
</div>
<div class="control-group">
<label class="control-label" for="damage_type"><?php echo $lng->show("claim_damage_type")?>*</label>
<div class="controls">
<select id="damage_type" name="damage_type" <?php if ($par["id"] != 0) { echo "disabled"; } ?>>
<option value="0" <?php if ($damage_type == 0) echo "selected" ?>><?php echo $lng->show("claim_type_vehicle") ?></option>"
<option value="1" <?php if ($damage_type == 1) echo "selected" ?>><?php echo $lng->show("claim_type_goods") ?></option>"
</select>
</div>
</div>
<div class="control-group">
<label class="control-label" for="date_damage"><?php echo $lng->show("claim_date_damage"); ?>*</label>
<div class="controls">
<div class="input-append">
<input class="input-small" type="text" id="date_damage" name="date_damage" data-date-format="dd-mm-yyyy" placeholder="dd-mm-yyyy"
value="<?php echo $cfunc->convertDateFromDB(substr($date_damage, 0, 10)) ?>" required>
<span class="add-on"><i class="icon-calendar"></i></span>
</div>
</div>
</div>
<div class="control-group">
<label class="control-label" for="description"><?php echo $lng->show("claim_description")?>*</label>
<div class="controls">
<textarea class="input-xxlarge" rows="4" id="description" name="description" required><?php echo $description;?></textarea>
</div>
</div>
<div class="control-group">
<label class="control-label" for="choice"><?php echo $lng->show("claim_choice")?>*</label>
<div class="controls controls-row">
<select id="choice" name="choice" onchange="changeChoice();">
<option value="1" <?php if (isset($driver)&& $driver != 0) echo "selected" ?>><?php echo $lng->show("claim_driver") ?></option>"
<option value="2" <?php if (isset($subcontractor)&& $subcontractor != 0) echo "selected" ?>><?php echo $lng->show("claim_subcontractor") ?></option>"
<option value="3" <?php if ($personel != "") echo "selected" ?>><?php echo $lng->show("claim_personel") ?></option>"
</select>
</div>
</div>
<div id="driver-container" class="control-group">
<label class="control-label" for="driver"><?php echo $lng->show("claim_driver")?>*</label>
<div class="controls controls-row">
<select id="driver" name="driver">
<?php
$result = $db->q("SELECT * FROM ERP_drivers");
foreach ($result as $a) {
if ($driver == $a["driver_id"]) {
echo "<option value=".$a["driver_id"]." selected>".$a["driver_name"]."</option>";
}else{
echo "<option value=".$a["driver_id"].">".$a["driver_name"]."</option>";
}
}
?>
</select>
</div>
</div>
<div id="subcontractor-container" class="control-group">
<label class="control-label" for="subcontractor"><?php echo $lng->show("claim_subcontractor")?>*</label>
<div class="controls controls-row">
<select id="subcontractor" name="subcontractor">
<?php
$subcontractors = $db->q("SELECT r.relatie_id, r.relatie_naam
FROM relaties AS r INNER JOIN relatie_lijsten AS l
ON r.relatie_id = l.relatie_lijst_relatie_id
WHERE l.relatie_lijst_relatieslijst_id = 23");
foreach($subcontractors as $s){
if ($subcontractor == $s["relatie_id"]) {
echo "<option value=\"".$s["relatie_id"]."\" selected>".$s["relatie_naam"]."</option>";
}else{
echo "<option value=\"".$s["relatie_id"]."\">".$s["relatie_naam"]."</option>";
}
}
?>
</select>
</div>
</div>
<div id="personel-container" class="control-group">
<label class="control-label" for="personel"><?php echo $lng->show("claim_personel")?>*</label>
<div class="controls controls-row">
<select id="personel" name="personel">
<?php
$personelList = $db->q("SELECT * FROM `erp_gebruiker` WHERE `actief` =1");
foreach($personelList as $p){
if ($personel == $p["gebruiker_id"]) {
echo "<option value=\"".$p["gebruiker_id"]."\" selected>".$p["naam"]."</option>";
}else{
echo "<option value=\"".$p["gebruiker_id"]."\">".$p["naam"]."</option>";
}
}
?>
</select>
</div>
</div>
<div id="vehicle-container" class="control-group">
<label class="control-label" for="vehicle"><?php echo $lng->show("claim_choice_vehicle")?>*</label>
<div class="controls controls-row">
<select id="vehicle" name="vehicle" onchange="changeVehicle();">
<?php
$result = $db->q("SELECT * FROM ERP_vehicles");
foreach ($result as $v) {
if ($vehicle == $v["vehicle_id"]) {
echo "<option value=".$v["vehicle_id"]." selected>".$v["vehicle_name"]."</option>";
}else{
echo "<option value=".$v["vehicle_id"].">".$v["vehicle_name"]."</option>";
}
}
?>
</select>
</div>
</div>
<div class="control-group">
<label class="control-label" for="license_plate"><?php echo $lng->show("claim_license_plate")?></label>
<div class="controls">
<input type="text" id="license_plate" name="license_plate" value="<?php echo $license_plate; ?>">
</div>
</div>
<div class="control-group">
<label class="control-label" for="faulty"><?php echo $lng->show("claim_faulty")?></label>
<div class="controls controls-row">
<select id="faulty" name="faulty">
<option value="0" <?php if ($faulty == 0) echo "selected"; ?>><?php echo $clng->show("no")?></option>";
<option value="1" <?php if ($faulty == 1) echo "selected"; ?>><?php echo $clng->show("yes")?></option>";
</select>
</div>
</div>
<div class="control-group">
<label class="control-label" for="file_insurance"><?php echo $lng->show("claim_insurance_nr")?></label>
<div class="controls">
<input type="text" id="file_insurance" name="file_insurance" value="<?php echo $file_insurance?>">
</div>
</div>
<div class="control-group">
<label class="control-label" for="damage_amount"><?php echo $lng->show("claim_damage_amount")?></label>
<div class="controls">
<input type="number" step="0.01" id="damage_amount" name="damage_amount" value="<?php echo $damage_amount?>">
</div>
</div>
<div class="control-group">
<label class="control-label" for="exemption"><?php echo $lng->show("claim_exemption")?></label>
<div class="controls">
<input type="number" step="0.01" id="exemption" name="exemption" value="<?php echo $exemption?>">
</div>
</div>
<div class="control-group">
<label class="control-label" for="amount_payed"><?php echo $lng->show("claim_amount_payed")?></label>
<div class="controls">
<input type="number" step="0.01" id="amount_payed" name="amount_payed" value="<?php echo $amount_payed?>">
</div>
</div>
<div class="control-group">
<label class="control-label" for="status"><?php echo $lng->show("claim_status")?></label>
<div id="choice" class="controls">
<select id="status" name="status">
<option value="1" <?php if ($status == 1) echo "selected"; ?>><?php echo $lng->show("claim_status_handling")?></option>";
<option value="2" <?php if ($status == 2) echo "selected"; ?>><?php echo $lng->show("claim_status_handled")?></option>";
</select>
</div>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-primary"><?php echo $knop?></button>
<button type="button" class="btn" onclick="javascript:location.href='<?php echo $url?>'"><?php echo $clng->show("cancel")?></button>
</div>
</form>
<script>
$(function () {
$("input,select,textarea").not("[type=submit]").jqBootstrapValidation();
changeChoice();
// alert("blablabla");
});
$("#date_damage").datepicker({format:'dd-mm-yyyy'});
function changeChoice() {
var c = $("#choice :selected").val();
if (c == "1") {
$("#driver-container").show();
$("#subcontractor-container").hide();
$("#personel-container").hide();
} else if (c == "2") {
$("#driver-container").hide();
$("#subcontractor-container").show();
$("#personel-container").hide();
} else {
$("#driver-container").hide();
$("#subcontractor-container").hide();
$("#personel-container").show();
}
changeVehicle()
}
function changeVehicle() {
var choice = $("#choice :selected").val();
var vehiclePlate = $("#vehicle :selected").val();
var licensePlate = '<?php if ($par["id"] == 0 ) { echo ""; } else { echo $license_plate; }?>'
if (choice == "1" || choice == "3") {
$("#vehicle-container").show();
$("#license_plate").prop('disabled', true);
showLicense(vehiclePlate);
$("#license_plate").val(data[0]);
} else {
$("#vehicle-container").hide();
$("#license_plate").prop('disabled', false);
//$("#license_plate").val(licensePlate);
}
}
function showLicense(plate) {
$.ajax({
type: 'POST',
url: 'index.php?page=claims&ajax=getplate',
dataType: 'json',
data: { plate: plate },
success: function(data) {
$("#license_plate").val(data[0]);
}
});
}
</script>
Found it. It seemds that some validation-code is the bad guy. Everything works fine when I put this in comment:
<script>
$(function () {
//$("input,select,textarea").not("[type=submit]").jqBootstrapValidation();
changeChoice();
});
...
</script>
I don't really have an idea why, I'm still pretty new with this JavaScript/JQuery stuff, but at least I can find a workaround for the validation that line provided.

Categories