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.
Related
my HTML code
<section>
<div class="container " style="height: 55vh;">
<div class="row">
<div class="col-1 icon-content-wraper">
<h2> add products</h2>
</div>
</div>
<div class="row">
<div class="col-1">
<form id="form" action="newadd.php" method="post">
<div class="col-1 ">
add product:
<div class="input-container">
<input type="text" id="reference" name="reference" placeholder=" " required>
<label for="reference">Product reference number</label>
</div>
<div class="input-container">
<input type="text" id="stock_amount" name="stock_amount" placeholder=" " required>
<label for="stock_amount">Product stock amount</label>
</div>
<div class="input-container">
<input type="text" id="product_name" name="product_name" placeholder=" " required>
<label for="product_name">Product name</label>
</div>
Product cattegory: <div class="input-container">
<select class="sort" name="category" id="category">
<option value="1">Salty
<option value="2" selected="">Sweet
<option value="3" selected="">Chocolate
<option value="4" selected="">Sour
</select>
</div>
<div class="input-container">
<textarea id="description" name="description" rows="4" cols="50" required></textarea>
<span for="description">description</span>
</div>
<div class="input-container">
<input type="text" id="price" name="price" placeholder=" " required>
<label for="price">Product price</label>
</div>
<div class="input-container">
<input type="text" id="tax" name="tax" placeholder=" " required>
<label for="tax">Product tax</label>
</div>
<div class="input-container">
<input type="text" id="discount" name="discount" placeholder=" " required>
<label for="discount">Product discount</label>
</div>
</div>
<div class="col-1 mt-60">
<input id="Add" class="btn-standard" type="submit" name="Add" value="Add" />
</div>
</form>
</div>
</div>
</div>
</section>
<div class="article-progress-bar"></div>
<script type="text/javascript" >
$(document).ready(function(){
$("#form").submit(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "newadd.php",
dataType:"json",
data:{
Reference:$("#reference").val(),
Stock: $("#stock_amount").val(),
ProductName: $("#product_name").val(),
Category: $("#category: selected").text(),
Description: $("#description").val(),
Price: $("#price").val(),
Tax: $("#tax").val(),
Discount: $("#discount").val()
},
success: function(response){
alert(response);
if (response == 1){
window.location="cms-view-products.php";
}
else if (response == 0){
alert("error to add data");
}
}
})
});
});
</script>
my PHP code
<?php
....
//Extract the data that was sent to the server
if($_SERVER['REQUEST_METHOD'] === 'POST'){
$reference = $_POST['reference'];
$stock = $_POST['Stock'];
$name = $_POST['ProductName'];
$category = $_POST['category'];
$description = $_POST['Description'];
$price = $_POST['Price'];
$tax = $_POST['Tax'];
$discount = $_POST['Discount'];
//Convert to PHP array
$dataArray = [
$Tag => [
"Reference" => $reference,
"StockAmount" => $stock
],
"Name" => $name,
"Description" => $description,
"Category" => $category,
"Tax" => $tax,
"Rating" => " ",
"Discount" => $discount,
"Price" => $price
];
//Add the new product to the database
$insertResult = $collection->insertOne($dataArray);
//Echo result back to user
if($insertResult->getInsertedCount()){
echo 1;
}
else {
echo 0;
}
}
else {
echo 'connection Error';
}
The error is that it adds null fields to the database plus:
Warning: Undefined array key "Stock" in C:\xampp\htdocs\newadd.php on line 19
Warning: Undefined array key "ProductName" in C:\xampp\htdocs\newadd.php on line 20
Warning: Undefined array key "Description" in C:\xampp\htdocs\newadd.php on line 22
Warning: Undefined array key "Price" in C:\xampp\htdocs\newadd.php on line 23
etc.
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,
);
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
I'm attempting my hand at ajax which i'm not the greatest at, my code for the page:
<?php
include('includes/db_connection.php');
include('includes/sessions.php');
include('includes/functions.php');
include('includes/header.php');
include('includes/navbar-logged.php');
require_once('api-sape.php');
// init sape
$sape = new SapeApi();
$userId = $sape->login(SAPE_USER, SAPE_PASS);
?>
<style type="text/css">
.modal-loading {
top: 0;
left: 0;
position: fixed;
z-index: 999;
width: 100%;
height: 100%;
background-color: rgba(0,0,0,0.1);
display: none;
}
.modal-loading .loading {
width: 64px;
height: 64px;
margin: 200px auto;
}
</style>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<div class="modal-loading"><div class="loading"><img src="http://wz.sera5902.myjino.ru/loading.gif"></div></div>
<?php
// isset
if (isset($_POST['search'])) {
// show var_dump
if ($member == SAPE_USER) { showPre($_POST); }
// try...
try
{
// vars
$sapeURLID = $_POST['url_id'];
$sapeDepth = $_POST['domain_level'];
$sapeInInG = $_POST['indexed_in_google'];
$sapeOrder = $_POST['order'];
$sapePLeve = $_POST['page_level'];
$sapeSdays = $_POST['search_days'];
$sapeKwdos = $_POST['keyword'];
$sapeKwpla = $_POST['keyword_placement'];
$sapeSdmoz = $_POST['site_in_dmoz'];
$sapeExtLi = $_POST['external_links'];
$sapePriFr = $_POST['price_from'];
$sapePriTo = $_POST['price_to'];
$sapeMajC1 = $_POST['mj_cf_1'];
$sapeMajC2 = $_POST['mj_cf_2'];
$sapeMajT1 = $_POST['mj_tf_1'];
$sapeMajT2 = $_POST['mj_tf_2'];
$sapePageN = $_POST['page_number'];
// arrays
$zones = array();
if (isset($_POST['zones'])) {
if (count($_POST['zones']) > 0) {
foreach ($_POST['zones'] as $key => $value) {
$zones[] = $value;
}
}
}
// arrays
$cats = array();
if (isset($_POST['categories'])) {
if (count($_POST['categories']) > 0) {
foreach ($_POST['categories'] as $key => $value) {
$cats[] = $value;
}
}
}
// xml-rpc query
$userSearch = $sape->search($sapeURLID, array("order"=>$sapeOrder,"domain_level"=>$sapeDepth,"domain_zones"=>$zones,"categories"=>$cats,"flag_blocked_in_google"=>$sapeInInG,"level_from"=>$sapePLeve,"days_old_whois"=>$sapeSdays,"words"=>str_replace(" ", "+", $sapeKwdos),"words_type"=>$sapeKwpla,"in_dmoz"=>$sapeSdmoz,"ext_links"=>$sapeExtLi,"pr_from"=>$sapePriFr,"pr_2"=>$sapePriTo,"mj_cf_1"=>$sapeMajC1,"mj_cf_2"=>$sapeMajC2,"mj_tf_1"=>$sapeMajT1,"mj_tf_2"=>$sapeMajT2), $sapePageN);
// is there any results?
if (count($userSearch) == 0) {
stderr("No results with those filters, try again with more options selected.");
}
// loop results
foreach ($userSearch as $val1) {
// ignore blank urls
if (!empty($val1['url'])) {
if ($member == SAPE_USER) {
echo "<pre>";
echo "<br />";
echo "<b>ID:</b> " . $val1['id'];
echo "<br />";
echo "<b>URL:</b> " . $val1['url'];
echo "<br />";
echo "<br />";
}
foreach ($val1['pages'] as $key => $val2) {
$urlCheck = DB::getInstance()->selectOne(
'
SELECT DISTINCT site_sape_url, site_uri
FROM `sites`
WHERE `site_sape_url` = :site_sape_url
AND `site_uri` = :site_uri',
[
'site_sape_url' => $val1['url'],
'site_uri' => $val2['uri']
]
);
// count check
if (!count($urlCheck)) {
// ten op for the site level
$level = ($val2['uri'] == "/") ? '1' : $val2['level'];
// get site ip
$ip = gethostbyname(parse_url($val1['url'], PHP_URL_HOST));
// insertion
DB::getInstance()->insert(
'sites',
[
'site_sape_id' => $val1['id'],
'site_sape_url' => $val1['url'],
'site_uri_id' => $val2['id'],
'site_uri' => $val2['uri'],
'site_uri_price' => $val2['price'],
'site_level' => $level,
'site_pages_in_google' => $val1['nof_pages_in_google'],
'site_ip' => $ip,
'site_added' => date('Y-m-d H:i:s')
]);
}
////////////////////////////////////////////////////////////////////////////////////
// have we already checked the link stats?
/* $already = DB::getInstance()->select("SELECT * FROM `metrics` WHERE `metrics_url`='".trim($val1['url'] . $val2['uri'])."'");
if (!count($already)) {
// vars
$fURL = returnDomDetails(trim($val1['url'] . $val2['uri']));
// domdetailer
$domMajestic = json_decode($fURL);
if ($domMajestic) {
// avoid "PHP Notice: Trying to get property of non-object" warnings
DB::getInstance()->insert(
'metrics',
[
'metrics_user_id' => 1,
'metrics_url' => $metricsURL,
'metrics_moz_links' => $domMajestic->mozLinks,
'metrics_mozPA' => $domMajestic->mozPA,
'metrics_mozDA' => $domMajestic->mozDA,
'metrics_mozRank' => $domMajestic->mozRank,
'metrics_mozTrust' => $domMajestic->mozTrust,
'metrics_FB_comments' => $domMajestic->FB_comments,
'metrics_FB_shares' => $domMajestic->FB_shares,
'metrics_google_plus_one' => $domMajestic->google_plus_one,
'metrics_pinterest_pins' => $domMajestic->pinterest_pins,
'metrics_linkedin' => $domMajestic->linkedin,
'metrics_majesticLinks' => $domMajestic->majesticLinks,
'metrics_majesticRefDomains' => $domMajestic->majesticRefDomains,
'metrics_majesticCF' => $domMajestic->majesticCF,
'metrics_majesticTF' => $domMajestic->majesticTF,
'metrics_date' => date('Y-m-d H:i:s')
]);
}
} */
////////////////////////////////////////////////////////////////////////////////////
if ($member == SAPE_USER) {
echo "<br />";
echo "<b>------------->Page ID:</b> " . $val2['id'];
echo "<br />";
echo "<b>------------->Page:</b> " . $val2['uri'];
echo "<br />";
echo "<br />";
}
}
if ($member == SAPE_USER) {
echo "</pre>";
}
}
}
// show var_dump
if ($member == SAPE_USER) { showPre($userSearch); }
// message
stdmsg('Search complete, view the results here.');
} catch (SapeApiException $e) {
if ($e->getMessage() == "SAPE.RU: Search result is too big :o(") {
stderr('Your search query has too many results, try refining your search options to be more specific.');
} else {
stderr($e->getMessage());
}
}
}
// get the logged in users id
$row = get_logged_in_users_details($member);
// the ID
$hID = $row['member_id'];
?>
<div class="panel panel-primary">
<div class="panel-heading">Search - To get a Link ID you need to create a project.</div>
<div class="panel-body">
<form id="search-form" action="search.php" method="post" class="form-horizontal container-fluid" role="form">
<div class="row form-group">
<div class="col-sm-6 text-right">
<label for="txtLinkID" class="control-label">Link ID:</label>
</div>
<div class="col-sm-6">
<select id="txtLinkID" name="url_id" class="form-control" required="required">
<?php
$rows = DB::getInstance()->select('SELECT * FROM `projects` WHERE `project_member_id`='.$hID);
?>
<?php foreach ($rows as $row) { ?>
<option value="<?php echo htmlspecialchars($row['project_sape_link_id']) ?>"><?php echo htmlspecialchars($row['project_sape_link_id']) ?></option>
<?php } ?>
</select>
</div>
</div>
<div class="row form-group">
<div class="col-sm-6 text-right">
<label for="txtLevelDepth" class="control-label">Domain Level:</label>
</div>
<div class="col-sm-6">
<select id="txtLevelDepth" name="domain_level" class="form-control" required="required">
<?php
$level = array(0 => "1",1 => "2",2 => "3");
?>
<?php foreach ($level as $key => $value) { ?>
<option value="<?php echo htmlspecialchars($key) ?>"><?php echo htmlspecialchars($value) ?></option>
<?php } ?>
</select>
</div>
</div>
<div class="row form-group">
<div class="col-sm-6 text-right">
<label for="txtLevelDepth" class="control-label">Nesting Pages:</label>
</div>
<div class="col-sm-6">
<select id="txtLevelDepth" name="page_level" class="form-control" required="required">
<?php
$nesting = array(0 => "page_level_1",1 => "page_level_2",2 => "page_level_3");
?>
<?php foreach ($nesting as $key => $value) { ?>
<option value="<?php echo htmlspecialchars($key) ?>"><?php echo htmlspecialchars($value) ?></option>
<?php } ?>
</select>
</div>
</div>
<div class="row form-group">
<div class="col-sm-6 text-right">
<label for="" class="control-label">Categories:</label>
</div>
<div class="col-sm-6">
<?php
$rows = DB::getInstance()->select('SELECT * FROM `categories`');
?>
<?php foreach ($rows as $row) { ?>
<input type="checkbox" name="categories[]" value="<?php echo htmlspecialchars($row['cat_sape_id']) ?>"> - <?php echo htmlspecialchars($row['cat_name']) ?><br>
<?php } ?>
</div>
</div>
<div class="row form-group">
<div class="col-sm-6 text-right">
<label for="" class="control-label">Zones:</label>
</div>
<div class="col-sm-6">
<?php
$rows = DB::getInstance()->select('SELECT * FROM `zones`');
?>
<?php foreach ($rows as $row) { ?>
<input type="checkbox" name="zones[]" value="<?php echo htmlspecialchars($row['zone_sape_id']) ?>"> - <?php echo htmlspecialchars($row['zone_name']) ?><br>
<?php } ?>
</div>
</div>
<div class="row form-group">
<div class="col-sm-6 text-right">
<label for="" class="control-label">Indexed in Google:</label>
</div>
<div class="col-sm-6">
<select id="" name="indexed_in_google" class="form-control" required="required">
<?php
$depth = array(0 => "Yes",1 => "No",2 => "Does not matter");
?>
<?php foreach ($depth as $key => $value) { ?>
<option value="<?php echo htmlspecialchars($key) ?>"><?php echo htmlspecialchars($value) ?></option>
<?php } ?>
</select>
</div>
</div>
<div class="row form-group">
<div class="col-sm-6 text-right">
<label for="" class="control-label">Site in DMOZ:</label>
</div>
<div class="col-sm-6">
<select id="" name="site_in_dmoz" class="form-control" required="required">
<?php
$dmoz = array(1 => "No", 0 => "Yes");
?>
<?php foreach ($dmoz as $key => $value) { ?>
<option value="<?php echo htmlspecialchars($key) ?>"><?php echo htmlspecialchars($value) ?></option>
<?php } ?>
</select>
</div>
</div>
<div class="row form-group">
<div class="col-sm-6 text-right">
<label for="txtCR" class="control-label">Site Must Be older Than (in days):</label>
</div>
<div class="col-sm-6">
<input type="text" id="" name="search_days" value="0" class="form-control" size="40" required="required"/>
</div>
</div>
<div class="row form-group">
<div class="col-sm-6 text-right">
<label for="txtCR" class="control-label">Site Must Contain This Keyword:</label>
</div>
<div class="col-sm-6">
<input type="text" id="" name="keyword" value="" class="form-control" size="40" />
</div>
</div>
<div class="row form-group">
<div class="col-sm-6 text-right">
<label for="txtCR" class="control-label">Keyword Should Be:</label>
</div>
<div class="col-sm-6">
<select id="" name="keyword_placement" class="form-control" required="required">
<?php
$depth = array(0 => "On the page somewhere",1 => "In the <title>Keyword(s)</title> tags");
?>
<?php foreach ($depth as $key => $value) { ?>
<option value="<?php echo htmlspecialchars($key) ?>"><?php echo htmlspecialchars($value) ?></option>
<?php } ?>
</select>
</div>
</div>
<div class="row form-group">
<div class="col-sm-6 text-right">
<label for="txtCR" class="control-label">No More Than This Number of External Links On-Page:</label>
</div>
<div class="col-sm-6">
<input type="text" id="" name="external_links" value="0" class="form-control" size="40" required="required"/>
</div>
</div>
<div class="row form-group">
<div class="col-sm-6 text-right">
<label for="txtCR" class="control-label">Price (From):</label>
</div>
<div class="col-sm-6">
<input type="text" id="" name="price_from" value="0" class="form-control" size="40" required="required"/>
</div>
</div>
<div class="row form-group">
<div class="col-sm-6 text-right">
<label for="txtCR" class="control-label">Price (To):</label>
</div>
<div class="col-sm-6">
<input type="text" id="" name="price_to" value="500" class="form-control" size="40" required="required"/>
</div>
</div>
<div class="row form-group">
<div class="col-sm-6 text-right">
<label for="txtCR" class="control-label">Majestic CF (Min):</label>
</div>
<div class="col-sm-6">
<input type="text" id="" name="mj_cf_1" value="0" class="form-control" size="40" required="required"/>
</div>
</div>
<div class="row form-group">
<div class="col-sm-6 text-right">
<label class="control-label">Majestic CF (Max):</label>
</div>
<div class="col-sm-6">
<input type="text" id="" name="mj_cf_2" value="0" class="form-control" size="40" required="required"/>
</div>
</div>
<div class="row form-group">
<div class="col-sm-6 text-right">
<label class="control-label">Majestic TF (Min):</label>
</div>
<div class="col-sm-6">
<input type="text" id="" name="mj_tf_1" value="0" class="form-control" size="40" required="required"/>
</div>
</div>
<div class="row form-group">
<div class="col-sm-6 text-right">
<label class="control-label">Majestic TF (Max):</label>
</div>
<div class="col-sm-6">
<input type="text" id="" name="mj_tf_2" value="0" class="form-control" size="40" required="required"/>
</div>
</div>
<div class="row form-group">
<div class="col-sm-6 text-right">
<label for="" class="control-label">Order Results By:</label>
</div>
<div class="col-sm-6">
<select id="" name="order" class="form-control" required="required">
<?php
$depth = array(9 => "Lowest price first",19 => "Highest price first",4 => "Category Descending",14 => "Category Ascending");
?>
<?php foreach ($depth as $key => $value) { ?>
<option value="<?php echo htmlspecialchars($key) ?>"><?php echo htmlspecialchars($value) ?></option>
<?php } ?>
</select>
</div>
</div>
<div class="row form-group">
<div class="col-sm-6 text-right">
<label class="control-label"># Of Pages Of Results:</label>
</div>
<div class="col-sm-6">
<select id="" name="page_number" class="form-control" required="required">
<?php for ($x = 1; $x <= 5; $x++) { ?>
<option value="<?php echo $x ?>"><?php echo $x ?></option>
<?php } ?>
</select>
</div>
</div>
<div class="row form-group">
<div class="col-sm-6 text-right">
<label class="control-label" style="display: inline-block;"> </label>
</div>
<div class="col-sm-6 text-right">
<button type="submit" name="search" class="btn btn-default">Search</button>
<input type="hidden" name="hiddenID" value="<?php echo $hID; ?>" />
</div>
</div>
</form>
</div>
<div class="panel-footer">Search for links using <b>your</b> criteria.</div>
</div>
<script type="text/javascript">
$(document).ready(function(){
$('#search-form').submit(function(){
$('.modal-loading').fadeIn();
var url = $(this).attr('action');
$.post(url, $(this).serialize(), function(html){
$('.modal-loading').fadeOut();
var newDoc = document.open("text/html", "replace");
newDoc.write(html);
newDoc.close();
});
return false;
});
});
</script>
<?php
include('includes/footer.php');
Once the "search" is pressed, i wanted a loading .gif to appear to show the user it's working (this shows fine) the problem is, the form doesn't seem to be submitting, the if (isset($_POST['search'])) { is not being triggered for some reason, can anyone see anything i have missed?
This is the major problem with W3Schools and people following it.
if (isset($_POST['search'])) {
Will never be sent! Or triggered. You need to check the Network Tab for what all is going to the POST request.
You need to check with:
if (count($_POST) > 0) {
Or something that you are sending.
I have a strange issue with one form in Codeigniter. I am also using DataMapper PHP. So I have one form with two select statements with a couple of options. If one is selected the other one becomes 0 if the other is selected then the first one becomes 0. Any ideas why the strange behavior ?
Controller
public function edit($id)
{
// Check if the user is logged in
if (!$this->ion_auth->logged_in())
{
redirect('/');
}
elseif ($this->ion_auth->is_admin())
{
// Create Object
$predictions = new Prediction_model();
$predictions->where('id', $id)->get();
$categories = new Categories_model();
$bookmakers = new Bookmakers_model();
$categories->order_by('id', 'asc')->get();
$bookmakers->order_by('id', 'asc')->get();
// Default Object Options
$defaultCategory = new Categories_model();
$defaultCategory->where('id', $predictions->category_id)->get();
$defaultBookmaker = new Bookmakers_model();
$defaultBookmaker->where('id', $predictions->bookmaker_id)->get();
$recent_categories = array();
foreach ($categories as $category)
{
$single_category = array
(
'category_id' => $category->id,
'sport' => $category->sport,
);
array_push($recent_categories, $single_category);
}
$recent_bookmakers = array();
foreach ($bookmakers as $bookmaker)
{
$single_bookmaker = array
(
'bookmaker_id' => $bookmaker->id,
'bookmaker' => $bookmaker->bookmaker,
);
array_push($recent_bookmakers, $single_bookmaker);
}
// Validation rules
$rules = $this->prediction_model->rules;
$this->form_validation->set_rules($rules);
$data = array
(
'prediction_id' => $predictions->id,
'defaultCategory' => $defaultCategory->sport,
'defaultBookmaker' => $defaultBookmaker->bookmaker,
'eventDate' => $predictions->eventDate,
'event' => $predictions->event,
'tip' => $predictions->tip,
'bestOdd' => $predictions->bestOdd,
'bookmakers' => $recent_bookmakers,
'categories' => $recent_categories,
'admin_content' => 'admin/predictions/edit',
);
if ($this->input->post('submit'))
{
$predictions->eventDate = $this->input->post('eventDate');
$predictions->event = $this->input->post('event');
$predictions->tip = $this->input->post('tip');
$predictions->bestOdd = $this->input->post('bestOdd');
$predictions->bookmaker_id = $this->input->post('bookmaker');
$predictions->category_id = $this->input->post('icon');
}
if ($this->form_validation->run() == FALSE)
{
$this->parser->parse('admin/template_admin', $data);
}
else
{
$predictions->save();
redirect('admin/predictions/');
}
}
else
{
// NO ACCESS
}
} // function edit
and here is the VIEW:
<?php echo form_open('admin/predictions/edit/{prediction_id}', 'class="form-horizontal"'); ?>
<div class="form-group">
<label for="category" class="col-sm-2 control-label">Category</label>
<div class="col-sm-10">
<select name="icon" class="form-control">
<option selected='selected'>{defaultCategory}</option>
<option>--------</option>
{categories}
<option value="{category_id}">{sport}</option>
{/categories}
</select>
</div>
</div>
<div class="form-group">
<label for="event" class="col-sm-2 control-label">Event</label>
<div class="col-sm-10">
<input type="text" name="event" class="form-control" value="{event}">
</div>
</div>
<div class="form-group">
<label for="tip" class="col-sm-2 control-label">Tip</label>
<div class="col-sm-10">
<input type="text" name="tip" class="form-control" value="{tip}">
</div>
</div>
<div class="form-group">
<label for="bookmaker" class="col-sm-2 control-label">Bookmaker</label>
<div class="col-sm-5">
<select name="bookmaker" class="form-control">
<option selected='selected'>{defaultBookmaker}</option>
<option>--------</option>
{bookmakers}
<option value="{bookmaker_id}">{bookmaker}</option>
{/bookmakers}
</select>
</div>
<label for="bestOdd" class="col-sm-2 control-label">Odd</label>
<div class="col-sm-3">
<input type="text" name="bestOdd" class="form-control" value="{bestOdd}">
</div>
</div>
<div class="form-group">
<label for="date" class="col-sm-2 control-label">Date</label>
<div class="col-sm-4">
<div class="input-group">
<input size="16" name="eventDate" type="text" class="form-control eventDate" value="{eventDate}" readonly>
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<input type="submit" name="submit" value="Save" class="btn btn-success btn-lg">
</div>
</div>
<?php echo form_close(); ?>