Custom filter datatables serverside not working in codeigniter 3 - codeigniter

Custom filter datatables serverside not working in codeigniter 3 but no error, with join table database ... anyone can help me ? thx
MODEL
Rekap_m.php
var $column_order = array(null, 'bidang', 'skpd', 'kode', 'masalah', 'nomor', 'rincian_masalah', 'tahun_cipta', 'rak', 'dos', 'retensi', 'ket');
var $column_search = array('bidang', 'kode', 'nomor', 'skpd');
var $order = array('id_arsip' => 'asc');
private function _get_datatables_query()
{
if ($this->input->post('bidang')) {
$this->db->where('id_bidang', $this->input->post('bidang'));
}
if ($this->input->post('skpd')) {
$this->db->like('skpd', $this->input->post('skpd'));
}
if ($this->input->post('kode')) {
$this->db->like('kode', $this->input->post('kode'));
}
if ($this->input->post('masalah')) {
$this->db->like('masalah', $this->input->post('masalah'));
}
$this->db->select('*');
$this->db->from('arsip');
$this->db->join('bidang', 'bidang.id_bidang = arsip.id_bidang');
$i = 0;
foreach ($this->column_search as $item) {
if (#$_POST['search']['value']) {
if ($i === 0) {
$this->db->group_start();
$this->db->like($item, $_POST['search']['value']);
} else {
$this->db->or_like($item, $_POST['search']['value']);
}
if (count($this->column_search) - 1 == $i)
$this->db->group_end();
}
$i++;
}
if (isset($_POST['order'])) {
$this->db->order_by($this->column_order[$_POST['order']['0']['column']], $_POST['order']['0']['dir']);
} else if (isset($this->order)) {
$order = $this->order;
$this->db->order_by(key($order), $order[key($order)]);
}
}
function get_datatables()
{
$this->_get_datatables_query();
if (#$_POST['length'] != -1)
$this->db->limit(#$_POST['length'], #$_POST['start']);
$query = $this->db->get();
return $query->result();
}
function count_filtered()
{
$this->_get_datatables_query();
$query = $this->db->get();
return $query->num_rows();
}
function count_all()
{
$this->db->from('arsip');
return $this->db->count_all_results();
}
public function get_list_bidangs()
{
$this->db->select('*');
$this->db->from('arsip');
$this->db->join('bidang', 'bidang.id_bidang = arsip.id_bidang');
$this->db->order_by('id_arsip', 'asc');
$query = $this->db->get();
$result = $query->result();
$bidangs = array();
foreach ($result as $row) {
$bidangs[] = $row->bidang;
}
return $bidangs;
}
CONTROLLER
Rekap.php
function __construct()
{
parent::__construct();
check_not_login();
$this->load->model('rekap_m');
}
public function index()
{
$bidangs = $this->rekap_m->get_list_bidangs();
$opt = array('' => 'Semua Bidang');
foreach ($bidangs as $id_bidang) {
$opt[$id_bidang] = $id_bidang;
}
$data['form_bidang'] = form_dropdown('', $opt, '', 'id="bidang" class="form-control"');
$this->template->load('template', 'rekap/rekap_data', $data);
}
function ajax_list()
{
$list = $this->rekap_m->get_datatables();
$data = array();
$no = #$_POST['start'];
foreach ($list as $arsip) {
$no++;
$row = array();
$row[] = $no . ".";
$row[] = $arsip->bidang;
$row[] = $arsip->skpd;
$row[] = $arsip->kode;
$row[] = $arsip->masalah;
$row[] = $arsip->nomor;
$row[] = $arsip->rincian_masalah;
$row[] = $arsip->tahun_cipta;
$row[] = $arsip->rak;
$row[] = $arsip->dos;
$row[] = $arsip->retensi;
$row[] = $arsip->ket;
// add html for action
$data[] = $row;
}
$output = array(
"draw" => #$_POST['draw'],
"recordsTotal" => $this->rekap_m->count_all(),
"recordsFiltered" => $this->rekap_m->count_filtered(),
"data" => $data,
);
// output to json format
echo json_encode($output);
}
public function rekap()
{
$this->load->model('bidang_m');
$data['bidang'] = $this->bidang_m->get()->result();
$this->template->load('template', 'rekap/rekap_data', $data);
}
public function del($id)
{
$this->arsip_m->del($id);
if ($this->db->affected_rows() > 0) {
echo "<script>alert('Data Berhasil dihapus'); </script>";
}
echo "<script>window.location='" . site_url('rekap') . "'; </script>";
}
VIEW
rekap_data.php
<div class="row">
<!-- DataTable with Hover -->
<div class="col-lg-12">
<div class="card mb-4">
<div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
<div class="col-md-4 offset-md-4">
<form id="form-filter">
<div class="form-horizontal">
<div class="form-group">
<div class="col-sm-9">
<div class="form-group">
<label for="bidang" class="col-sm-4 control-label">Bidang</label>
<?php echo $form_bidang; ?>
</div>
<div class="form-group">
<label for="skpd" class="col-sm-4 control-label">SKPD</label>
<input type="text" class="form-control" id="skpd">
</div>
<div class="form-group">
<label for="kode" class="col-sm-4 control-label">Kode</label>
<input type="text" class="form-control" id="kode">
</div>
<div class="form-group">
<label for="masalah" class="col-sm-4 control-label">Masalah</label>
<textarea class="form-control" id="masalah"></textarea>
</div>
<div class="form-group">
<button type="button" id="btn-filter" class="btn btn-primary">Filter</button>
<button type="button" id="btn-reset" class="btn btn-default">Reset</button>
</div>
</div>
</div>
</div>
</form>
</div>
</div>
<div class="table-responsive p-3">
<table class="table align-items-center table-flush table-hover" id="dataTableHover">
<thead class="thead-light">
<tr>
<th>#</th>
<th>Bidang</th>
<th>SKPD</th>
<th>Kode</th>
<th>Masalah</th>
<th>Nomor</th>
<th>Rincian</th>
<th>Tahun</th>
<th>Rak</th>
<th>Dos</th>
<th>Retensi</th>
<th>Keterangan</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
</div>
<script type="text/javascript">
var table;
$(document).ready(function() {
table = $('#dataTableHover').DataTable({
"processing": true,
"serverSide": true,
"ajax": {
"url": "<?php echo site_url('rekap/ajax_list') ?>",
"type": "POST",
"data": function(data) {
data.id_bidang = $('#bidang').val();
data.skpd = $('#skpd').val();
data.kode = $('#kode').val();
data.masalah = $('#masalah').val();
}
},
"columnDefs": [{
"targets": [0],
"orderable": false,
}, ],
});
$('#btn-filter').click(function() {
table.ajax.reload();
});
$('#btn-reset').click(function() {
$('#form-filter')[0].reset();
table.ajax.reload();
});
});
</script>
the code above is the code that I use, there is no error but not working ... is there something wrong with my code, I ask for advice on what corrections if there are errors

Related

My form is not inserting even tho it produces "success" message

I'm using Ajax + Datatable + Codeigniter. My target is to insert my form into my DB. However, it is not inserting. My current codes produces successful state alert. However, it is not inserting. Is there anything I missed? Additionally, i checked my image file path and it is still empty after insert. Any help will be appreciated. Thank you.
Views:
<div class="table-responsive">
<br/>
<button type="button" id="add_button" data-toggle="modal" data-target="#userModal" class="btn btn-info btn-lg">Add</button>
<br /><br />
<table id="user_datas" class="table table-bordered table-striped">
<thead>
<tr>
<th width="10%">Image</th>
<th width="35%">First Name</th>
<th width="35%">Last Name</th>
<th width="10%">Edit</th>
<th width="10%">Delete</th>
</tr>
</thead>
</table>
</div>
</div>
</body>
</html>
<div id="userModal" class="modal fade">
<div class="modal-dialog">
<form method="post" id="user_form" enctype="multipart/form-data" >
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Add User</h4>
</div>
<div class="modal-body">
<input type="text" name="firstname" id="firstname" class="form-control" />
<br />
<input type="text" name="lastname" id="lastname" class="form-control" />
<br />
<input type="file" name="user_image" id="user_image" />
<span id="user_uploaded_image"></span>
</div>
<div class="modal-footer">
<input type="hidden" name="user_id" id="user_id" />
<input type="submit" name="action" id="action" class="btn btn-success" value="Add" />
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</form>
</div>
</div>
Ajax:
$(document).ready(function(){
$('#add_button').click(function(){
$('#user_form')[0].reset();
$('.modal-title').text("Add User");
$('#action').val("Add");
$('#user_uploaded_image').html('');
})
var dataTable = $('#user_datas').DataTable({
"processing":true,
"serverSide":true,
"order":[],
"ajax":{
url:"<?php echo base_url() . 'profile/fetch_user'; ?>",
type:"POST"
},
"columnDefs":[
{
"targets":[0, 3, 4],
"orderable":false,
},
],
});
$(document).on('submit', '#user_form', function(event){
event.preventDefault();
var firstName = $('#firstname').val();
var lastName = $('#lastname').val();
var extension = $('#user_image').val().split('.').pop().toLowerCase();
if(extension != '')
{
if(jQuery.inArray(extension, ['gif','png','jpg','jpeg']) == -1)
{
alert("Invalid Image File");
$('#user_image').val('');
return false;
}
}
if(firstName != '' && lastName != '')
{
$.ajax({
url:"<?php echo base_url() . 'profile/user_action'?>",
method:'POST',
data:new FormData(this),
contentType:false,
processData:false,
success:function(data)
{
alert('Successful');
$('#user_form')[0].reset();
$('#userModal').modal('hide');
dataTable.ajax.reload();
}
});
}
else
{
alert("Fields are Required");
}
});
$(document).on('click', '.update', function(){
var user_id = $(this).attr("id");
$.ajax({
url:"<?php echo base_url(); ?>profile/fetch_single_user",
method:"POST",
data:{user_id:user_id},
dataType:"json",
success:function(data)
{
$('#userModal').modal('show');
$('#firstname').val(data.firstname);
$('#lastname').val(data.lastname);
$('.modal-title').text("Edit User");
$('#user_id').val(user_id);
$('#user_uploaded_image').html(data.user_image);
$('#action').val("Edit");
}
})
});
});
Controller:
function fetch_user(){
$this->load->model("profile_repository");
$fetch_data = $this->profile_repository->make_datatables();
$data = array();
foreach($fetch_data as $row)
{
$sub_array = array();
$sub_array[] = '<img src="'.base_url().'public/assets/upload/'.$row->image.'" class="img-thumbnail" width="50" height="35" />';
$sub_array[] = $row->firstname;
$sub_array[] = $row->lastname;
$sub_array[] = '<button type="button" name="update" id="'.$row->userID.'" class="btn btn-warning btn-xs update">Update</button>';
$sub_array[] = '<button type="button" name="delete" id="'.$row->userID.'" class="btn btn-danger btn-xs delete">Delete</button>';
$data[] = $sub_array;
}
$output = array(
"draw" => intval(isset($_POST["action"]) && $_POST["action"]),
"recordsTotal" => $this->profile_repository->get_all_data(),
"recordsFiltered" => $this->profile_repository->get_filtered_data(),
"data" => $data
);
echo json_encode($output);
}
function user_action(){
if(isset($_POST["action"]) == "Add")
{
$insert_data = array(
'firstname' => $this->input->post('firstname'),
'lastname' => $this->input->post("lastname"),
'image' => $this->upload_image()
);
$this->load->model('profile_repository');
$this->profile_repository->insert_crud($insert_data);
echo 'Data Inserted';
}
if(isset($_POST["action"]) == "Edit")
{
$user_image = '';
if($_FILES["user_image"]["name"] != '')
{
$user_image = $this->upload_image();
}
else
{
$user_image = $this->input->post("hidden_user_image");
}
$updated_data = array(
'firstname' => $this->input->post('firstname'),
'lastname' => $this->input->post('lastname'),
'image' => $user_image
);
$this->load->model('profile_repository');
$this->profile_repository->update_crud($this->input->post("user_id"), $updated_data);
echo 'Data Updated';
}
}
function upload_image()
{
if(isset($_FILES["user_image"]))
{
$extension = explode('.', $_FILES['user_image']['name']);
$new_name = rand() . '.' . $extension[1];
$destination = './public/assets/upload/' . $new_name;
move_uploaded_file($_FILES['user_image']['tmp_name'], $destination);
return $new_name;
}
}
function fetch_single_user()
{
$output = array();
$this->load->model("profile_repository");
$data = $this->profile_repository->fetch_single_user($_POST["user_id"]);
foreach($data as $row)
{
$output['firstname'] = $row->firstname;
$output['lastname'] = $row->lastname;
if($row->image != '')
{
$output['user_image'] = '<img src="'.base_url().'public/assets/upload/'.$row->image.'" class="img-thumbnail" width="50" height="35" /><input type="hidden" name="hidden_user_image" value="'.$row->image.'" />';
}
else
{
$output['user_image'] = '<input type="hidden" name="hidden_user_image" value="" />';
}
}
echo json_encode($output);
}
}
Model:
var $table = "users";
var $select_column = array("userID", "firstname", "lastname", "image");
var $order_column = array(null, "firstname", "lastname", null, null);
function make_query()
{
$this->db->select($this->select_column);
$this->db->from($this->table);
if(isset($_POST["search"]["value"]))
{
$this->db->like("firstname", $_POST["search"]["value"]);
$this->db->or_like("lastname", $_POST["search"]["value"]);
}
if(isset($_POST["order"]))
{
$this->db->order_by($this->order_column[$_POST['order']['0']['column']], $_POST['order']['0']['dir']);
}
else
{
$this->db->order_by('userID', 'DESC');
}
}
function make_datatables(){
$this->make_query();
if(isset($_POST["length"]) && $_POST["length"] != -1)
{
$this->db->limit($_POST['length'], $_POST['start']);
}
$query = $this->db->get();
return $query->result();
}
function get_filtered_data(){
$this->make_query();
$query = $this->db->get();
return $query->num_rows();
}
function get_all_data()
{
$this->db->select("*");
$this->db->from($this->table);
return $this->db->count_all_results();
}
function insert_crud($data)
{
$this->db->insert('users', $data);
}
function fetch_single_user($user_id)
{
$this->db->where("userID", $user_id);
$query=$this->db->get('users');
return $query->result();
}
function update_crud($user_id, $data)
{
$this->db->where("userID", $user_id);
$this->db->update("users", $data);
}
}
There was a mistake in
if(isset($_POST["action"]) == "Add")
isset function returning boolean, therefore your condition will return
if(true == "Add")
which return false.
your code return successful state because it was successful state for your ajax request (code 200), not your insert function
you should change your user_action to :
if(isset($_POST["action"])){
if($_POST["action"] == "Add")
{
$insert_data = array(
'firstname' => $this->input->post('firstname'),
'lastname' => $this->input->post("lastname"),
'image' => $this->upload_image()
);
$this->load->model('profile_repository');
$this->profile_repository->insert_crud($insert_data);
echo 'Data Inserted';
}
else if($_POST["action"] == "Edit")
{
$user_image = '';
if($_FILES["user_image"]["name"] != '')
{
$user_image = $this->upload_image();
}
else
{
$user_image = $this->input->post("hidden_user_image");
}
$updated_data = array(
'firstname' => $this->input->post('firstname'),
'lastname' => $this->input->post('lastname'),
'image' => $user_image
);
$this->load->model('profile_repository');
$this->profile_repository->update_crud($this->input->post("user_id"), $updated_data);
echo 'Data Updated';
}
}

[Codeigniter]Multiple upload cant insert to database and not uploading to directory

How to upload multiple images with Codeigniter 4.x ?
I tried to loop the do_upload function in my model but it's not working, and I tried another code that I got from GitHub but still, none of it works.
This is my view:
<div class="section-body">
<h2 class="section-title">Entry Group Passanger</h2>
<div class="row">
<div class="col-md-12">
<form action="<?= base_url('passanger/addgroup') ?>" method="POST" enctype="multipart/form-data">
<?php for($i=1;$i<=$pax['pax'];$i++) : ?>
<h5>Passanger ke-<?= $i ?></h5>
<div class="form-row">
<div class="col-md-6">
<label for="fullname">Fullname</label>
<input type="text" class="form-control" name="name[]">
<?= form_error('name', '<small class="text-danger pl-3">', '</small>'); ?>
</div>
<div class="col-md-6">
<label for="gender">Gender</label>
<select class="form-control select2-input" name="gender">
<option>-- Select Gender --</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
<option value="Other">Other</option>
</select>
<?= form_error('gender', '<small class="text-danger pl-3">', '</small>'); ?>
</div>
</div>
<div class="form-row">
<div class="col-md-12 mb-4 mt-2">
<label for="">Upload Passport</label>
<input type="file" name="upload_passport[]" id="input-file-now" class="dropify" />
</div>
</div>
this is my model :
public function addGroup()
{
$user = $this->db->get_where('user', ['username' => $this->session->userdata('username')])->row_array();
$pax = $this->getPaxById();
date_default_timezone_set('Asia/Jakarta');
$upload_image = $_FILES['upload_passport[]']['name'];
if ($upload_image) {
$config['upload_path'] = './assets/img/uploads/passport';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '2048';
$this->load->library('upload', $config);
for($i=0;$i<$pax['pax'];$i++) {
if ($this->upload->do_upload('upload_passport[$i]')) {
$new_image = $this->upload->data('file_name');
} else {
echo $this->upload->display_errors();
}
}
}
$name = $this->input->post("name[]");
$gender = $this->input->post("gender[]");
$birthdate = $this->input->post("birthdate[]");
$no_passport = $this->input->post("no_passport[]");
$expire_passport = $this->input->post("expire_passport[]");
$destination = $this->input->post("destination[]");
$date = $this->input->post("date[]");
$dp1 = "0";
$dp2 = "0";
$lunas = "0";
$type = "Group";
$status = "Not Complete";
$permission = "0";
$upload_passport = $new_image;
$upload_dp1 = "default.png";
$upload_dp2 = "default.png";
$date_created = date('d/m/Y H:i:s');
$data = [];
$jumlah = $pax['pax'];
for($x=0;$x<$jumlah;$x++) {
array_push($data, [
'name'=>$this->input->post("name[$x]"),
'id_user'=> $user['id_user'],
'gender'=>$this->input->post("gender[$x]"),
'birthdate'=>$this->input->post("birthdate[$x]"),
'no_passport'=> $this->input->post("no_passport[$x]"),
'expire_passport'=> $this->input->post("expire_passport[$x]"),
'destination'=> $this->input->post("destination[$x]"),
'date'=> $this->input->post("date[$x]"),
'dp1'=> $dp1,
'dp2'=> $dp2,
'lunas'=> $lunas,
'pax'=> $pax['pax'],
'type'=> $type,
'status'=> $status,
'permission'=> $permission,
'upload_passport'=> $new_image,
'upload_dp1'=> $upload_dp1,
'upload_dp2'=> $upload_dp2,
'date_created'=> $date_created
]);
var_dump($data); die;
}
$this->db->insert_batch("passanger", $data);
}
What I want to get is:
array('','','upload_image'), array('','','upload_image')
When insert it to database but when I do it the upload just gets output null and it's not even uploaded to my uploads directory. I would really appreciate it if you help me, I've been stuck on this for 3 days. Thank you.
for ($i=0; $i < sizeof($_FILES['image']['name']) ; $i++) {
$_FILES['file']['name'] = $_FILES['image']['name'][$i];
$_FILES['file']['type'] = $_FILES['image']['type'][$i];
$_FILES['file']['tmp_name'] = $_FILES['image']['tmp_name'[$i];
$_FILES['file']['error'] = $_FILES['image']['error'][$i];
$_FILES['file']['size'] = $_FILES['image']['size'][$i];
$config['upload_path'] = PRODUCT_IMAGE_UPLOAD_PATH;
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['encrypt_name'] = TRUE;
$this->load->library('upload', $config);
if ($this->upload->do_upload('file')){
$images[] = $this->upload->data('file_name');
}else {
echo $this->upload->display_errors();
}
}
Try this in Codeigniter 4
in your controller add this
$image_model = new App\Models\Images(); // Your model name that is load your model
if($imagefiles = $this->request->getFiles())
{
foreach($imagefiles['uploadImages'] as $img)
{
if ($img->isValid() && ! $img->hasMoved())
{
$image_name = $img->getRandomName(); // This is applicable if you want to change the name of the images
if($image_model->save_images($image_name))
{
$img->move(WRITEPATH.'uploads/images/ads', $image_name); // WRITEPATH.'uploads/images/ads' is the part you wish to save you file to
}
}
}
}
In your Model e.g Image model i have a method call save_images()as this
use Codeigniter\Model
class Images extends Model{
public function save_images($image = '')
{
// We set the column 'name' to be allow for data entry into the db. note this is mandatory for now.
// hope it will change in feature. 'name' is the column in database table where you will save the image name
// this command the CI4 db to select only the image column in the database table
$this->allowedFields = ['name'];
return $this->db->table('images')->insert(['name' => $image]);
// echo $sql = $this->db->getLastQuery();
}
}
Then in your html file input, do this
<form action="" method="post" enctype="multipart/form-data">
<div class="form-group">
<input type="file" name="uploadImages[]" multiple>
</div>
</form>
I hope this will work for you

Codeigniter Repotrs page problem with dates

I am developing a project using Codeigniter framework and in the reports page i need to have a form that has datatables structure so i can generate reports by day,month and year. but i dont know how to use datatables.
i have tried to add code like for example where it was written Y-m i added d-m-y but it doesn't work
Reports Controller:
defined('BASEPATH') OR exit('No direct script access allowed');
class Reports extends Admin_Controller
{
public function __construct()
{
parent::__construct();
$this->data['page_title'] = 'Stores';
$this->load->model('model_reports');
}
/*
* It redirects to the report page
* and based on the year, all the orders data are fetch from the database.
*/
public function index()
{
if(!in_array('viewReports', $this->permission)) {
redirect('dashboard', 'refresh');
}
$today_year = date('Y');
if($this->input->post('select_year')) {
$today_year = $this->input->post('select_year');
}
$parking_data = $this->model_reports->getOrderData($today_year);
$this->data['report_years'] = $this->model_reports->getOrderYear();
$final_parking_data = array();
foreach ($parking_data as $k => $v) {
if(count($v) > 1) {
$total_amount_earned = array();
foreach ($v as $k2 => $v2) {
if($v2) {
$total_amount_earned[] = $v2['net_amount'];
}
}
$final_parking_data[$k] = array_sum($total_amount_earned);
}
else {
$final_parking_data[$k] = 0;
}
}
$this->data['selected_year'] = $today_year;
$this->data['company_currency'] = $this->company_currency();
$this->data['results'] = $final_parking_data;
$this->render_template('reports/index', $this->data);
}
}
**Reports Model:**
<?php
class Model_reports extends CI_Model
{
public function __construct()
{
parent::__construct();
}
/*getting the total months*/
private function months()
{
return array('01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12');
}
/* getting the year of the orders */
public function getOrderYear()
{
$sql = "SELECT * FROM orders WHERE paid_status = ?";
$query = $this->db->query($sql, array(1));
$result = $query->result_array();
$return_data = array();
foreach ($result as $k => $v) {
$date = date('Y', $v['date_time']);
$return_data[] = $date;
}
$return_data = array_unique($return_data);
return $return_data;
}
// getting the order reports based on the year and moths
public function getOrderData($year)
{
if($year) {
$months = $this->months();
$sql = "SELECT * FROM orders WHERE paid_status = ?";
$query = $this->db->query($sql, array(1));
$result = $query->result_array();
$final_data = array();
foreach ($months as $month_k => $month_y) {
$get_mon_year = $year.'-'.$month_y;
$final_data[$get_mon_year][] = '';
foreach ($result as $k => $v) {
$month_year = date('Y-m', $v['date_time']);
if($get_mon_year == $month_year) {
$final_data[$get_mon_year][] = $v;
}
}
}
return $final_data;
}
}
}
**View index**
<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
<!-- Content Header (Page header) -->
<section class="content-header">
<h1>
Reports
</h1>
<ol class="breadcrumb">
<li><i class="fa fa-dashboard"></i> Home</li>
<li class="active">Reports</li>
</ol>
</section>
<!-- Main content -->
<section class="content">
<!-- Small boxes (Stat box) -->
<div class="row">
<div class="col-md-12 col-xs-12">
<form class="form-inline" action="<?php echo base_url('reports/') ?>" method="POST">
<div class="form-group">
<label for="date">Year</label>
<select class="form-control" name="select_year" id="select_year">
<?php foreach ($report_years as $key => $value): ?>
<option value="<?php echo $value ?>" <?php if($value == $selected_year) { echo "selected"; } ?>><?php echo $value; ?></option>
<?php endforeach ?>
</select>
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
</div>
<br /> <br />
<div class="col-md-12 col-xs-12">
<?php if($this->session->flashdata('success')): ?>
<div class="alert alert-success alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
<?php echo $this->session->flashdata('success'); ?>
</div>
<?php elseif($this->session->flashdata('error')): ?>
<div class="alert alert-error alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
<?php echo $this->session->flashdata('error'); ?>
</div>
<?php endif; ?>
<div class="box">
<div class="box-header">
<h3 class="box-title">Total - Report</h3>
</div>
<!-- /.box-header -->
<div class="box-body">
<div class="chart">
<canvas id="barChart" style="height:250px"></canvas>
</div>
</div>
<!-- /.box-body -->
</div>
<!-- /.box -->
<div class="box">
<div class="box-header">
<h3 class="box-title">Total Paid Orders - Report Data</h3>
</div>
<!-- /.box-header -->
<div class="box-body">
<table id="datatables" class="table table-bordered table-striped">
<thead>
<tr>
<th>Month - Year</th>
<th>Amount</th>
</tr>
</thead>
<tbody>
<?php foreach ($results as $k => $v): ?>
<tr>
<td><?php echo $k; ?></td>
<td><?php
echo $company_currency .' ' . $v;
//echo $v;
?></td>
</tr>
<?php endforeach ?>
</tbody>
<tbody>
<tr>
<th>Total Amount</th>
<th>
<?php //echo $company_currency . ' ' . array_sum($parking_data); ?>
<?php echo array_sum($results); ?>
</th>
</tr>
</tbody>
</table>
</div>
<!-- /.box-body -->
</div>
<!-- /.box -->
</div>
<!-- col-md-12 -->
</div>
<!-- /.row -->
</section>
<!-- /.content -->
</div>
<!-- /.content-wrapper -->
<script type="text/javascript">
$(document).ready(function() {
$("#reportNav").addClass('active');
});
var report_data = <?php echo '[' . implode(',', $results) . ']'; ?>;
$(function () {
/* ChartJS
* -------
* Here we will create a few charts using ChartJS
*/
var areaChartData = {
labels : ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
datasets: [
{
label : 'Electronics',
fillColor : 'rgba(210, 214, 222, 1)',
strokeColor : 'rgba(210, 214, 222, 1)',
pointColor : 'rgba(210, 214, 222, 1)',
pointStrokeColor : '#c1c7d1',
pointHighlightFill : '#fff',
pointHighlightStroke: 'rgba(220,220,220,1)',
data : report_data
}
]
}
//-------------
//- BAR CHART -
//-------------
var barChartCanvas = $('#barChart').get(0).getContext('2d')
var barChart = new Chart(barChartCanvas)
var barChartData = areaChartData
barChartData.datasets[0].fillColor = '#00a65a';
barChartData.datasets[0].strokeColor = '#00a65a';
barChartData.datasets[0].pointColor = '#00a65a';
var barChartOptions = {
//Boolean - Whether the scale should start at zero, or an order of magnitude down from the lowest value
scaleBeginAtZero : true,
//Boolean - Whether grid lines are shown across the chart
scaleShowGridLines : true,
//String - Colour of the grid lines
scaleGridLineColor : 'rgba(0,0,0,.05)',
//Number - Width of the grid lines
scaleGridLineWidth : 1,
//Boolean - Whether to show horizontal lines (except X axis)
scaleShowHorizontalLines: true,
//Boolean - Whether to show vertical lines (except Y axis)
scaleShowVerticalLines : true,
//Boolean - If there is a stroke on each bar
barShowStroke : true,
//Number - Pixel width of the bar stroke
barStrokeWidth : 2,
//Number - Spacing between each of the X value sets
barValueSpacing : 5,
//Number - Spacing between data sets within X values
barDatasetSpacing : 1,
//String - A legend template
legendTemplate : '<ul class="<%=name.toLowerCase()%>-legend"><% for (var i=0; i<datasets.length; i++){%><li><span style="background-color:<%=datasets[i].fillColor%>"></span><%if(datasets[i].label){%><%=datasets[i].label%><%}%></li><%}%></ul>',
//Boolean - whether to make the chart responsive
responsive : true,
maintainAspectRatio : true
}
barChartOptions.datasetFill = false
barChart.Bar(barChartData, barChartOptions)
})
</script>

ajax form request from a while - confuse variable

I want to send a form with a button from a while, but I have a problem. If post the button, the form confuse the variable. E.g: i post the button with id 1, and the script get the variable from the last input.
Code:
index:
<?php
$res = getProdus();
foreach($res as $row) { ?>
<form action="addtocart.php" method="POST">
<div class="col-12 col-sm-6 col-md-4 single_gallery_item women wow fadeInUpBig" data-wow-delay="0.2s">
<div class="product-img">
<img src="img/product-img/product-1.jpg" alt="">
<div class="product-quicview">
<i class="ti-plus"></i>
</div>
</div>
<div class="product-description">
<h4 class="product-price">$39.90</h4>
<p>Jeans midi cocktail dress</p>
<input type="hidden" name="addtcart" value="<?=$row['ID'];?>">
<button type="submit" class="add-to-cart-btn">ADD TO CART</button>
</div>
</div>
</form>
<?php } ?>
the ajax request:
$(document).ready(function() {
$('form').submit(function(event) {
var formData = {
'addtcart' : $('input[name=addtcart]').val()
};
$.ajax({
type : 'POST',
url : 'addtocart.php',
data : formData,
dataType : 'json',
encode : true
})
.done(function(data) {
console.log(data);
});
event.preventDefault();
});
});
and the addtocart.php
<?php
include("includes/functions.php");
session_start();
$errors = array(); // array to hold validation errors
$data = array(); // array to pass back data
if (empty($_POST['addtcart']))
$errors['addtcart'] = 'Este necesar produsul id-ului.';
if ( ! empty($errors)) {
$data['success'] = false;
$data['errors'] = $errors;
} else {
$ok = AddToCart(filtrare($_POST['addtcart']), getSpec("username", "users", "email", $_SESSION['magazin-user']));
if($ok == 1) {
$data['success'] = true;
$data['message'] = 'Success!';
} else {
$data['success'] = false;
$errors['mysqli'] = "Nu s-a realizat bine query-ul.";
$data['errors'] = $errors;
}
}
echo json_encode($data);
?>
Replace your button code with this
<button type="submit" value="<?=$row['ID'];?>" class="add-to-cart-btn">ADD TO CART</button>
and after that replace you
make changes to your script code
$(".add-to-cart-btn").click(function() {
var formData = {
'addtcart' : $(this).val()
};
.
.
.
and your rest of the code.

how search between date using post in codeignitier

Dear Expert need Help first see my view code in codeigniter :
<div class="form-group">
<label for="tglawal" class="col-sm-2 control-label">Periode</label>
<div class="col-sm-3">
<div class="input-group date">
<div class="input-group-addon">
<i class="fa fa-calendar"></i>
</div>
<input type="date" class="form-control" name="tglawal" id="tglawal">
</div>
</div>
<div class="col-sm-3">
<div class="input-group date">
<div class="input-group-addon">
<i class="fa fa-calendar"></i>
</div>
<input type="date" class="form-control" name="tglakhir" id="tglawal1">
</div>
</div>
</div>
and this my model code :
private function _get_datatables_query()
{
//add custom filter here
if($this->input->post('tglawal'))
{
$this->db->where('b.tglawal', $this->input->post('tglawal'));
}
if($this->input->post('tglakhir'))
{
$this->db->where('b.tglakhir', $this->input->post('tglakhir'));
}
}
public function get_datatables()
{
$this->_get_datatables_query();
if($_POST['length'] != -1)
$this->db->limit($_POST['length'], $_POST['start']);
$query = $this->db->get();
return $query->result();
}
and my controller if i get the important code is:
public function index()
{
$this->load->helper('url');
$this->load->helper('form');
$this->load->view('infokunjungan_view', $data);
}
else redirect(base_url());
}
public function ajax_list()
{
$list = $this->Infokunjungan->get_datatables();
$data = array();
$no = $_POST['start'];
foreach ($list as $infokunjungan) {
$no++;
$row = array();
$row[] = "<td style='vertical-align:middle'><center>{$no}<center></td>";
$row[] = "<td style='font-size:9px; vertical-align:left;'>{$infokunjungan->tglawal}<center></td>";
$row[] = "<td style='font-size:9px; vertical-align:left;'>{$infokunjungan->tglakhir}<center></td>";
$output = array(
"draw" => $_POST['draw'],
"recordsTotal" => $this->Infokunjungan->count_all(),
"recordsFiltered" => $this->Infokunjungan->count_filtered(),
"data" => $data,
);
//output to json format
echo json_encode($output);
}
the problem is if searching between two date tglawal and tglakhir
im using between 2016-12-04 and 2016-12-04 output display will empty
but if using between 2016-12-04 and 2016-12-06 output success where is my problem or maybe im using where or i have to use like?
You need to use the >= and <= operator.
In your model try the below.
if($this->input->post('tglawal'))
{
$this->db->where('b.tglawal >=', $this->input->post('tglawal')); //assuming this is your begining (from) date
}
if($this->input->post('tglakhir'))
{
$this->db->where('b.tglakhir <=', $this->input->post('tglakhir')); //assuming this is your end(to) date
}
The above will search for the between dates including the dates selected.
Use the operator depending on the beginning and ending variable.

Resources