I'm working on CodeIgniter project,. In my web-app I'm filtering my data-tables processing on server using drop-down lists with selecting multiple values from drop-down list box. I'm getting a proper output.
My view code is:
<div class="content-wrapper">
<div class="box-body">
<form name="listproperty" action="" method="post" role="form" id="form-filter">
<div class="row">
<div class="col-md-3">
<label>Area: </label>
<select class="form-control", name="area_name" id="area_name">
<option value="0">Select Area</option>
<?php
$area_id;
foreach ($areaList as $area) { ?>
<option value="<?= $area->area_id_primary; ?>" <?php if ($area->area_id_primary == $area_id) { echo "selected='selected'"; } ?>><?= $area->area_name; ?></option>
<?php } ?>
</select>
</div>
<div class="col-md-3">
<label>City: </label>
<select class="form-control" name="city_name" id="city_name" multiple="">
<option value="">Select City</option>
<?php $ct = explode(' ', $city);
foreach ($propertyCityList as $propertyCity) {
$selected = false;
foreach ($ct as $usercity) {
if ($usercity == $propertyCity->city_id_primary) {
$selected = true;
break;
}
} ?>
<option value="<?= $propertyCity->city_id_primary; ?>" <?php if($selected === true) { echo "selected='selected'"; } ?>><?= $propertyCity->city_name; ?></option>
<?php } ?>
</select>
</div>
</div>
<div class="row"> </div>
<div class="row">
<div class="pull-right">
<div class="col-md-12">
<button type="button" id="btn-filter" class="btn btn-success" style="margin-right: 25px;">Filter</button>
<button type="button" id="btn-reset" class="btn btn-default">Reset</button>
</div>
</div>
</div>
</form>
</div><hr>
<div class="box-body">
<table class="table table-striped table-bordered" id="listpropertyData" cellspacing="0" width="100%">
<thead>
<tr>
<th width="10%">Added Date</th>
<th width="10%">ASYS No.</th>
<th width="18%">Address</th>
<th width="10%">City</th>
<th width="15%" style="text-align: center;">Action</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Added Date</th>
<th>ASYS No.</th>
<th>Address</th>
<th>City</th>
<th style="text-align: center;">Action</th>
</tr>
</tfoot>
</table>
</div>
<script type="text/javascript">
var property;
$(document).ready(function() {
$("#area_name").select2();
$("#city_name").select2();
property = $('#listpropertyData').DataTable({
"processing": true,
"serverSide": true,
"ajax": {
"url": "<?= base_url('Controller/getPropertyDatatable'); ?>",
"type": "POST",
"dataType": "JSON",
"data": function ( data ) {
data.area_name = $('#area_name').val();
data.city_name = $('#city_name').val();
}
},
"dom": '<"top"fli>rt<"bottom"p><"clear">',
"lengthMenu": [[25, 50, 100, 200, -1], [25, 50, 100, 200, "All"]],
"columnDefs": [
{
"targets":[7],
"orderable":false
},
],
});
$('.dataTables_filter input[type="search"]').css(
{'width':'450px','display':'inline-block'}
);
$('#btn-filter').click(function(){ //button filter event click
property.ajax.reload(); //just reload table
});
$('#btn-reset').click(function(){ //button reset event click
$('#form-filter')[0].reset();
property.ajax.reload();
window.location.reload(); //just reload table
});
});
</script>
My controller code:
public function listProperty()
{
# code...
$data['areaList'] = $this->property_model->areaList();
$data['propertyCityList'] = $this->property_model->propertyCityList();
$this->global['pageTitle'] = 'RoxAI-ePro : Property List';
$this->loadViews("property/listProperty", $this->global, $data, NULL);
}
public function getPropertyDatatable()
{
# code...
$listProperty = $this->property_model->getPropertyDatatable();
$data = array();
foreach ($listProperty as $property) {
# code...
$added_on=$property->property_added_on;
$added_on_date = str_replace('/', '-', $added_on);
$property_added_on_date=date('d/m/Y', strtotime($added_on_date));
$row = array();
$row[] = $property_added_on_date;
$row[] = $property->property_asys_number;
$row[] = $property->property_address;
$row[] = $property->city_name;
$row[] = 'Action';
$data[] = $row;
}
$output = array(
'draw' => $_POST['draw'],
'recordsTotal' => $this->property_model->countPropertyAll(),
'recordsFiltered' => $this->property_model->countPropertyFiltered(),
'data' => $data,
);
echo json_encode($output);
}
My question is how I can pass that drop-down list values in URL so I can get same result directly if I'm trying to copy-paste URL and open it in another browser with same selection of values in drop-down?
Related
I have a jQuery dataTable that depending on the option you select in a previous Select shows you some data or others. By default it shows those of the first option and so far everything is correct.
The problem comes when I select the second option, that the dataTable seems to be unconfigured and shows me all the results in a row without respecting the Paginate, also if I try to sort by name or another field it will show me the first option again. The same is also true if I try to change the table page.
I don't know where the error is.
I attach some images as a sample:
First option (everything works perfect): image
On select second option: image , image2
If i try to click on tabs 1 to 7 or p.ex. order the column
Universitatautomatically shows this (results of the first selector but without respecting the design of the table) image
First option selector code:
<div class="panel-body">
<div class="tab-content">
<div class="tab-pane fade in active no-info" id="tab1default">
<?php if($isAdmin){ ?>
<input type="hidden" id="niuProfessor" value="<?php echo $niu; ?>">
<div class="padding-bottom-20">
<select id="selectIfAdmin">
<option id="mineAdmin" value="mineAdmin">Les meves Universitats</option>
<option id="allAdmin" value="allAdmin">Totes les Universitats</option>
</select>
</div>
<!--<div id="showByGrau" class="padding-bottom-20" >
<select id="selectGrauAdmin">
<option value="-1">Tots els graus </option>
<?php foreach($degrees as $degree): ?>
<option value="<?php echo $degree->codiEstudis; ?>"><?php echo $degree->nomGrau; ?></option>
<?php endforeach; ?>
</select>
</div>-->
<?php } ?>
<div id="acordsTeacherAdmin" class="table-responsive">
<table class="table table-hover cell-border display compact" id="dev-table">
<thead>
<tr>
<th>Universitat</th>
<!-- <th>Grau</th>-->
<th>Places</th>
<th>Mesos</th>
<th>Període</th>
<!--<th>Assignatures</th>-->
<th><em class="fa fa-cog"></em></th>
</tr>
</thead>
<tbody id="taulaAcordsCoordinador">
<?php foreach ($agree as $ag): ?>
<tr >
<td><?php echo $ag->nomUniversitat; ?></td>
<!--<td><?php echo $ag->nomGrau; ?></td>-->
<td><?php echo $ag->plaçes; ?></td>
<td><?php echo $ag->mesos; ?></td>
<td><?php echo $ag->període; ?></td>
<!--<td align="center">
Opinar
</td>-->
<td align="center">
Publicar / Acord
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
</div>
</div>
<div id="debug">
</div>
</div>
</div>
Second option code (TaulaAcordsCoordinador.php):
<?php foreach ($agree as $ag): ?>
<tr >
<td><?php echo $ag->nomUniversitat; ?></td>
<td><?php echo $ag->plaçes; ?></td>
<td><?php echo $ag->mesos; ?></td>
<td><?php echo $ag->període; ?></td>
<!--<td align="center">
Opinar
</td>-->
<td align="center">
Publicar / Acord
</td>
</tr>
<?php endforeach; ?>
EventListener:
,$(document).on("change", "#selectIfAdmin", function(e){
e.preventDefault();
var data = {};
data.niu = $("#niuProfessor").val();
data.filtre = $(this).val();
filtrarAcordsAdmin(data);
})
Function with Ajax call:
function filtrarAcordsAdmin(data){
$.ajax({
type: "POST",
url: "perfil.php/" + "filtrarAcordsAdmin",
data: {"data":JSON.stringify(data)},
success: function(t, e, c) {
$("#taulaAcordsCoordinador").html(t);
/*if(data.filtre === "allAdmin"){$("#showByGrau").css('display','block');}
else{$("#showByGrau").css('display','none');}*/
},
error: function(t, e) {
}
})}
Perfi.php code:
case 'filtrarAcordsAdmin':
$actionName = "filtrarAcordsAdmin";
$data['data'] = $_POST['data'];
array_push($parameters,$data);
break;
filtrarAcordsAdmin controller:
public function filtrarAcordsAdmin($parameters){
$data = json_decode($parameters[0]['data']);
require_once 'models/TeachersModel.php';
require_once 'models/ConvenisModel.php';
$teachersModel = new TeachersModel();
$convenisModel = new ConvenisModel();
if($data->filtre == 'mineAdmin'){
$agree = $teachersModel->getAgreementsTeacher($data->niu);
}elseif ($data->filtre == 'allAdmin'){
$agree = $convenisModel->getConvenis();
}
$teachersModel->disconnect();
$convenisModel->disconnect();
$route = $this->view->show("TaulaAcordsCoordinador.php");
include($route);
}
Both functions getConvenis() and getAgreementsTeacher() are functions of a model that returns de result of a query into the BD like that:
public function getConvenis(){
try {
$consulta = $this->db->prepare('SELECT uni.nomUniversitat, uni.idUniversitat, es.nomGrau,co.codiConveni,co.codiCentreEstudis,ce.plaçes,ce.mesos,ce.període
FROM centreestudis ce, universitat_estudisuab un,universitats uni,estudisuab es,conveni co
WHERE ce.codiUniEstudis = un.codiUniEstudis
AND uni.idUniversitat = un.idUniversitat
AND un.codiEstudis = es.codiEstudis
AND co.codiCentreEstudis = ce.codiCentreEstudis
ORDER BY uni.nomUniversitat');
$consulta->execute();
$obj = $consulta->fetchAll(PDO::FETCH_OBJ);
} catch (Exception $e) {
}
return $obj;
}
public function getAgreementsTeacher($niu){
try {
$consulta = $this->db->prepare('SELECT ce.plaçes, ce.mesos, ce.període , un.nomUniversitat ,un.idUniversitat,co.codiConveni, eu.nomGrau
FROM professorscentre pr, centreestudis ce, universitat_estudisuab ue, estudisuab eu, universitats un, conveni co
WHERE pr.niuProfessor = ?
AND ce.codiCentreEstudis = pr.codiCentreEstudis
AND ue.codiEstudis = eu.codiEstudis
AND ce.codiUniEstudis = ue.codiUniEstudis
AND un.idUniversitat = ue.idUniversitat
AND co.codiCentreEstudis = ce.codiCentreEstudis
ORDER BY un.nomUniversitat');
$consulta->execute(array($niu));
$obj = $consulta->fetchAll(PDO::FETCH_OBJ);
return $obj;
} catch (Exception $e) {
}
}
I'm using the checkbox to sending an email that already selected. after the email sent, the status sendinvoice change to Y. everything is fine when I select 1 checkbox. but when I choose multiple checkboxes, the function only update 1 checkbox
How to make it can run update function with multiple checkboxes?
the view code for checkbox and button below
<button type="button" class="btn waves-effect waves-light btn-info" id="btn-sentcitilink"> Sent Email</button>
<?php
foreach($result as $row){
?>
<form method="post" action="<?php echo base_url(); ?>cms/emailcitilink" id="sentemailcitilink">
<?php
}
?>
<table id="myTable" class="table table-bordered table-striped">
<thead>
<tr>
<th>Send Invoice </th>
<th>Booking ID</th>
</tr>
</thead>
<tbody>
<?php
foreach($result as $row){
?>
<tr>
<td>
<?php if($row['sendinvoice'] == 'N'){ ?>
<div class="custom-control custom-checkbox">
<input type="checkbox" class="custom-control-input" name="books[]" id="tableDefaultCheck/<?php echo $row['booking_id']?>" value="<?php echo $row['booking_id']?>">
<label class="custom-control-label" for="tableDefaultCheck/<?php echo $row['booking_id'] ?>"></label>
</div>
<?php } ?>
<?php if($row['sendinvoice'] == 'Y'){ ?>
<div class="custom-control custom-checkbox">
<input type="checkbox" class="custom-control-input" id="tableDefaultCheck3" checked disabled>
<label class="custom-control-label" for="tableDefaultCheck3"></label>
</div>
<?php } ?>
</td>
<td>
<div class="hover-link">
<a href="<?php echo base_url(); ?>cms/transaction/view/<?php echo $row['_id'] ?>">
<?php echo $row['booking_id'] ?>
</a>
</div>
</td>
</tr>
<?php
}
?>
</tbody>
</table>
<script>
$(document).ready(function() {
$("#check-all").click(function() {
if ($(this).is(":checked"))
$(".check-item").prop("checked", true);
else // Jika checkbox all tidak diceklis
$(".check-item").prop("checked", false);
});
$("#btn-sentcitilink").click(function() {
var confirm = window.confirm("Apakah Anda mengirim email data-data ini?");
if (confirm)
$("#sentemailcitilink").submit();
});
});
</script>
The controller code
function emailtocitilink(){
$books = $_POST['books'];
$get_trans = $this->cms_model->get_transaction_by_list_trip($tripsData);
foreach($get_trans as $row){
$arr_data = array(
'booking_id' => $row['TRANSIDMERCHANT'],
);
array_push($arr, $arr_data);
}
$data = $this->data;
$data['result'] = $arr;
$datas = array(
'SendINVOICE' => "Y"
);
$insert = $this->cms_model->update_transaction($datas, $books);
redirect(base_url().'cms/citilinktransaction/');
}
Model
function get_transaction_by_list_trip($TripUUID){
return $this->mongo_db
->where_in('TripUUID', $TripUUID)
->where(array('PAYMENTCHANNEL' => 'TESTINGCHANNEL'))
->order_by(array('transaction_date' => 'desc'))
->get('tr_transaction');
}
function update_transaction($datas, $books){
return $this->mongo_db->where_in('TRANSIDMERCHANT', $books)
->set($datas)
->update('tr_transaction',['multi' => TRUE]);
}
On model, it should be 'multiple' => true
Use update_all to update multiple records:
$this->mongo_db
->set($datas, ["multi" => true])
->where_in('TRANSIDMERCHANT', $books)
->update_all('tr_transaction');
Hi im working on my workshop tools project.
Now i have some strange action sometimes when i pressed the add to cart button (mine was named pinjam) it just going back to the login page because the session destroyed. Anyone has this strange thing happened? or Can you help me?
The scenario is like this..
I pressed the add to cart button on one of much tools that can i borrow, then it post to the add_to_cart function on my controller and reload the #cart_content div on that page with new added data with jquery / ajax
Controller Siswa
function index(){
$data['guru'] = $this->model_akun->getnamaguru();
$data['data']=$this->model_alat->getAll();
$this->load->view('siswa/dashboard',$data);
}
function add_to_cart(){
if($this->model_alat->validate_add_cart_item() == TRUE){
// Check if user has javascript enabled
if($this->input->post('ajax') != '1'){
redirect('siswa'); // If javascript is not enabled, reload the page with new data
}else{
echo 'true'; // If javascript is enabled, return true, so the cart gets updated
}
}
}function show_cart(){
$this->load->view('siswa/cart');
}
Model_Alat
function validate_add_cart_item(){
$id = $this->input->post('id_alat'); // Assign posted id_alat to $id
$cty = $this->input->post('quantity'); // Assign posted quantity to $cty
//$this->db->where('id_alat', $id); // Select where id matches the posted id
$query = $this->db->query('select * from alat where id_alat="'.$id.'"')->result(); // Select the products where a match is found and limit the query by 1
//$ss = $this->input->post('ajax');
//echo $query['id_alat'];
//echo "<script>alert(".$cty.");
// </script>";
// Check if a row has been found
if($query > 0){
foreach ($query as $row){
$data = array(
'id' => $id,
'qty' => $cty,
'price' => '0',
'name' => $row->nama_alat
);
$this->cart->insert($data);
return TRUE;
}
// Nothing found! Return FALSE!
}else{
echo "<script>alert('FALSE no rows :(');</script>";
return FALSE;
}
}
JQUERY
<script>
$(document).ready(function() {
/*place jQuery actions here*/
var link = "/weteies/index.php/"; // Url to your application (including index.php/)
$("div.subalat form").submit(function() {
// Get the product ID and the quantity
var id = $(this).find('input[name=id_alat]').val();
var qty = $(this).find('input[name=quantity]').val();
$.post(link + "siswa/add_to_cart", { id_alat: id, quantity: qty, ajax: '1' },
function(data){
// Interact with returned data
if(data == 'true'){
$.get(link + "siswa/show_cart", function(cart){ // Get the contents of the url cart/show_cart
$("#cart_content").html(cart); // Replace the information in the div #cart_content with the retrieved data
});
}else{
alert("Product does not exist");
}
});
});
});
siswa/cart (for viewing the cart list)
##siswa/cart view
<div class="table-responsive">
<?php echo form_open('siswa/update_cart'); ?>
<table class="table table-bordered">
<thead >
<tr>
<th>Alat</th>
<th>Jumlah</th>
<!--<th>Total</th>-->
<th>Actions</th>
</tr>
</thead>
<tbody>
<?php $a=0; $b=0;foreach($this->cart->contents() as $items): ?>
<tr>
<!--<input type="hidden" id="id_peminjam" name="id_peminjam" value="'.$this->session->userdata('ses_id').'"/>-->
<td><?php echo form_hidden('rowid['.$a.']', $items['rowid']);
echo $items['name']; ?></td>
<td><?php echo form_input(array('name' => 'qty['.$a.']', 'value' => $items['qty'], 'maxlength' => '2'), '', 'class="form-control form-control-sm"'); ?></td>
<!--<td><button type="button" id="'.$items['rowid'].'" class="romove_cart btn btn-danger btn-sm">Cancel</button></td>-->
<td><?php echo form_submit('', 'Update', 'class="btn btn-accept btn-sm"');
$b=$a+1;?>
</tr>
<?php $a++; endforeach; ?>
</tbody>
</table>
<?php echo form_hidden('jumlah_alat', $b);
echo form_close();?>
<?php echo form_open('siswa/sub_cart'); ?>
<table class="table">
<tr>
<td >
<select name="id_guru" class="form-control form-control-sm">
<option>Pilih Guru</option>
<?php foreach($guru as $gurus): echo '<option value='.$gurus->id_akun.'>'. $gurus->nama .'</option>'; endforeach;?>
</select>
</td>
<td>
<?php $hitung=0; $b=0; foreach($this->cart->contents() as $items): ?>
<?php echo form_hidden('id_alat'.$hitung.'', $items['id']);
echo form_hidden('jumlah_pinjam'.$hitung.'', $items['qty']);
echo form_hidden('id_siswa', $this->session->userdata('ses_id'));
$b=$hitung+1;
$hitung++;
endforeach;
echo form_hidden('jumlah_alat', $b);
echo anchor('siswa/empty_cart', 'Hapus Semua', 'class="btn btn-danger btn-sm col-sm-5"'); ?>
<?php echo form_submit('', 'Pinjam!', 'class="btn btn-primary btn-sm col-sm-5"');?>
</td>
</tr>
</table>
<?php echo form_close(); ?>
</div>
FORM siswa/dashboard
<!DOCTYPE html>
<head>
<?php $this->load->view("admin/_partials/head.php") ?>
</head>
<body id="page-top">
<!-- Navbar-->
<?php $this->load->view("siswa/_partials/navbar.php") ?>
<div id="wrapper">
<!-- Sidebar-->
<?php $this->load->view("siswa/_partials/sidebar.php") ?>
<div id="content-wrapper">
<div class="container-fluid">
<div class="row ">
<div class="col-md-6">
<div class="card mb-3">
<h4 class="card-header">Alat Tersedia</h4>
<br>
<div class="row card-body">
<?php foreach ($data as $row) : ?>
<div class="col-md-6">
<div class="card mb-3">
<div class="card-header text-center"><?php echo $row->nama_alat;?>
</div>
<div class="card-body">
<div class="row">
<div class="col-md-7">
Tersedia
</div>
<div class="col-md-5">
<input value="<?php echo $row->jumlah;?>" class="form-control form-control-sm" readonly>
</div>
</div>
<div class="subalat">
<?php echo form_open(''); ?>
<div class="row">
<div class="col-md-7">
Mau Brp?
</div>
<div class="col-md-5">
<?php echo form_hidden('id_alat', $row->id_alat);
echo form_input('quantity', '1', 'maxlength="2" class="form-control form-control-sm"'); ?>
</div>
</div>
<br>
<?php echo form_submit('add', 'Pinjam','class="btn btn-success btn-block col-md"'); ?>
<?php echo form_close(); ?>
</div>
</div>
</div>
</div>
<?php endforeach;?>
</div>
</div>
</div>
<div class="col-md-6">
<div class="card mb-3">
<h4 class="card-header">List Pinjam</h4>
<!--<div class="card-body">-->
<div id="cart_content">
<?php $this->load->view('siswa/cart'); ?>
</div>
<!--</div>-->
<div class="card-footer small text-muted">
Jika jumlah alat nya 0(nol), alat akan dihapus. Page rendered in <strong>{elapsed_time}</strong> seconds.
</div>
</div>
</div>
</div><!-- /.row -->
</div><!-- /.content-fluid -->
<!-- Sticky Footer -->
<?php $this->load->view("siswa/_partials/footer.php") ?>
</div>
<!-- /.content-wrapper -->
</div>
<!-- /#wrapper -->
<?php $this->load->view("siswa/_partials/scrolltop.php") ?>
<!-- Modal-->
<?php $this->load->view("siswa/_partials/modal.php") ?>
<!-- Js-->
<?php $this->load->view("siswa/_partials/js.php") ?>
</body>
<script>
$(document).ready(function() {
/*place jQuery actions here*/
var link = "/weteies/index.php/"; // Url to your application (including index.php/)
$("div.subalat form").submit(function() {
// Get the product ID and the quantity
var id = $(this).find('input[name=id_alat]').val();
var qty = $(this).find('input[name=quantity]').val();
$.post(link + "siswa/add_to_cart", { id_alat: id, quantity: qty, ajax: '1' },
function(data){
// Interact with returned data
if(data == 'true'){
$.get(link + "siswa/show_cart", function(cart){ // Get the contents of the url cart/show_cart
$("#cart_content").html(cart); // Replace the information in the div #cart_content with the retrieved data
});
}else{
alert("Product does not exist");
}
});
});
});
</script>
</html>
Login controller
class Login extends CI_Controller{
function __construct(){
parent::__construct();
$this->load->model("model_login");
}
function index(){
$this->form_validation->set_rules('email', 'Email', 'required|trim|valid_email');
$this->form_validation->set_rules('password', 'Password', 'required|trim');
if($this->form_validation->run()==FALSE){
$session = $this->session->userdata('isLoggedin');
if($session == FALSE){
$this->load->view('login');
}
else{
redirect('');
}
}
else{
$email=$this->input->post('email');
$password=$this->input->post('password');
$cek_akun=$this->model_login->auth_akun($email,$password);
if($cek_akun->num_rows() > 0){
$user_data=$cek_akun->row_array();
$this->session->set_userdata('isLoggedin',TRUE);
$this->session->set_userdata('ses_id',$user_data['id_akun']);
$this->session->set_userdata('ses_nama',$user_data['nama']);
if($user_data['level']=='admin'){ //level admin
$this->session->set_userdata('level','admin');
redirect('admin');
}
else if($user_data['level']=='aspiran'){ //level aspiran
$this->session->set_userdata('level','aspiran');
redirect('aspiran');
}
else if($user_data['level']=='guru'){ //level guru
$this->session->set_userdata('level','guru');
redirect('guru');
}
else if($user_data['level']=='siswa'){ //level siswa
$this->session->set_userdata('level','siswa');
redirect('siswa');
}
}
else{
$this->load->view('login');
echo "<script>alert('Failed Login: Check your username and password!');
</script>";
}
}
}
function logout(){
$this->session->sess_destroy();
$url=base_url('');
redirect($url);}}
My function add to cart didn't adding a food when i click button add to cart.
Controller:Asiabuffet.php
class Asiabuffet extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->library('cart');
$this->load->model('food_model');
}
public function index()
{
$data['data']=$this->food_model->get_all_food();
$this->load->view("front/asiabuffet",$data);
}
function add_to_cart(){
$data = array(
'id' => $this->input->post('id_food'),
'name' => $this->input->post('judul'),
'qty' => $this->input->post('quantity'),
);
$this->cart->insert($data);
echo $this->show_cart();
}
function show_cart(){
$output = '';
$no = 0;
foreach ($this->cart->contents() as $items) {
$no++;
$output .='
<tr>
<td>'.$items['name'].'</td>
<td>'.$items['qty'].'</td>
<td><button type="button" id="'.$items['rowid'].'" class="remove_cart btn btn-danger btn-sm">Cancel</button></td>
</tr>
';
}
return $output;
}
function load_cart(){
echo $this->show_cart();
}
function delete_cart(){
$data = array(
'rowid' => $this->input->post('row_id'),
'qty' => 0,
);
$this->cart->update($data);
echo $this->show_cart();
}
}
Models:Food_model.php
class Food_model extends CI_Model{
function get_all_food(){
$result=$this->db->get('food');
return $result;
}
}
Views:front/asiabuffet.php
<div class="col-md-12">
<?php foreach ($data->result() as $row) : ?>
<table class="table table-form">
<tbody>
<tr>
<td><?php echo $row->judul;?></td>
<td>
<div class="form-group">
<div class="col-md-2"></div>
<div class="col-md-8">
<input type="number" name="quantity" id="<?php echo $row->id_food;?>" value="0" class="quantity form-control">
</div>
<div class="col-md-2"></div>
</div>
</td>
<td>
<div class="col-md-12 text-center">
<button class="btn btn-primary btn-submit-card" data-id_food="<?php echo $row->id_food;?>" data-judul="<?php echo $row->judul;?>" onclick="add_cart(<?php echo $row->id_food;?>)">Add To Cart</button>
</div>
</td>
</tr>
</tbody>
</table>
<?php endforeach;?>
</div>
<div class="col-md-4">
<h4>Shopping Cart</h4>
<table class="table table-striped">
<thead>
<tr>
<th>Items</th>
<th>Qty</th>
<th>Actions</th>
</tr>
</thead>
<tbody id="detail_cart">
</tbody>
</table>
Jquery on view
<script type="text/javascript">
$(document).ready(function(){
$('.add_cart').click(function(){
var id_food = $(this).data("id_food");
var judul = $(this).data("judul");
var quantity = $('#' + id_food).val();
$.ajax({
url : "<?php echo site_url('asiabuffet/add_to_cart');?>",
method : "POST",
data : {id_food: id_food, judul: judul, quantity: quantity},
success: function(data){
$('#detail_cart').html(data);
}
});
});
$('#detail_cart').load("<?php echo site_url('asiabuffet/load_cart');?>");
$(document).on('click','.remove_cart',function(){
var row_id=$(this).attr("id");
$.ajax({
url : "<?php echo site_url('asiabuffet/delete_cart');?>",
method : "POST",
data : {row_id : row_id},
success :function(data){
$('#detail_cart').html(data);
}
});
});
});
</script>
I don't know what to do... Actually I made 2 view to adding cart to other view named checkout but it still not added. So, I make table on the same page to see if the food that being clicked adding to table or not. And it still cannot added to table.
I explain briefly I created a table that shows all my products on video, where inside the container that contains it are two select, enclosed in a form, which pass values in order to populate the table in my db, and everything works perfectly. The only thing though that when I select more than one product the db correctly registers only the last one selected from the checkbox,place my code in order to reach my goal, that of being able to insert more products(impianto_id_campagna),for the same customer id (cliente_id_campagna), and event id (id_campagna_cliente):
code:
<?php
$messaggio = "";
if (isset($_POST['submit'])) {
include '../connessione.php';
$id_campagna_cliente = $connessione->real_escape_string($_POST['id_campagna_cliente']);
$cliente_id_campagna = $connessione->real_escape_string($_POST['cliente_id_campagna']);
$impianto_id_campagna = $connessione->real_escape_string($_POST['impianto_id_campagna']);
$connessione->query("INSERT INTO campagne_cliente (
id_campagna_cliente,
cliente_id_campagna,
impianto_id_campagna)
VALUES (
'$id_campagna_cliente',
'$cliente_id_campagna',
'$impianto_id_campagna')");
$messaggio = "Registrazione Completata!";
}
?>
<main>
<?php
include '../connessione.php';
$query_string = "SELECT * FROM store_locator WHERE store_locator.id NOT IN (SELECT impianto_id_campagna FROM campagne_cliente)";
$query = mysqli_query($connessione, $query_string);
?>
<?php
include '../connessione.php';
$query_string = "SELECT * FROM clienti";
$clienti = mysqli_query($connessione, $query_string);
?>
<?php
include '../connessione.php';
$query_string = "SELECT * FROM campagne_cliente
INNER JOIN clienti
ON clienti.cliente_id = campagne_cliente.cliente_id_campagna
INNER JOIN campagne
ON campagne.id_campagna = campagne_cliente.id_campagna_cliente GROUP BY cognome";
$campagne = mysqli_query($connessione, $query_string);
?>
<!-- Datatables initialization -->
<script>
// Basic example
$(document).ready(function () {
$('#dtBasicExample').DataTable();
$('.dataTables_length').addClass('bs-select');
});
</script>
<!-- Structured data: Breadcrumbs -->
<form method="post" action="index.php">
<div class="container-fluid text-center">
<div class="row">
<div class="col-md-6">
<select name="cliente_id_campagna" class="ciao colorful-select dropdown-primary" multiple searchable="Cerca il Cliente">
<option value="" disabled selected>Cliente</option>
<?php
while($row = mysqli_fetch_assoc($clienti)){ ?>
<option value="<?php echo $row['cliente_id'] ;?>"><?php echo $row['nome'].' '.$row['cognome'] ;?></option>
<?php } ?>
</select>
<script type="text/javascript">
// Material Select Initialization
$(document).ready(function() {
$('.ciao').material_select();
});
</script>
</div>
<div class="col-md-6">
<select name="id_campagna_cliente" class="ok colorful-select dropdown-primary" multiple searchable="Cerca la campagna">
<option value="" disabled selected>Cliente</option>
<?php
while($row = mysqli_fetch_assoc($campagne)){ ?>
<option value="<?php echo $row['id_campagna_cliente'] ;?>"><?php echo $row['nome'].' '.$row['cognome'].' INIZIO['.$row['data_inizio'].'] FINE['.$row['data_fine'].']' ;?></option>
<?php } ?>
</select>
<script type="text/javascript">
// Material Select Initialization
$(document).ready(function() {
$('.ok').material_select();
});
</script>
</div>
</div>
<div class="col-md-12">
<?php if ($messaggio != "") echo $messaggio . "<br><br>"; ?>
<table id="dtBasicExample" class="table table-striped table-bordered table-sm" cellspacing="0" width="100%">
<thead>
<tr>
<th class="th-sm">ID
<i class="fa fa-sort float-right" aria-hidden="true"></i>
</th>
<th class="th-sm">Cimasa
<i class="fa fa-sort float-right" aria-hidden="true"></i>
</th>
<th class="th-sm">Proprietaria
<i class="fa fa-sort float-right" aria-hidden="true"></i>
</th>
<th class="th-sm">Concessionaria
<i class="fa fa-sort float-right" aria-hidden="true"></i>
</th>
<th class="th-sm">City
<i class="fa fa-sort float-right" aria-hidden="true"></i>
</th>
<th class="th-sm">Latitudine
<i class="fa fa-sort float-right" aria-hidden="true"></i>
</th>
<th class="th-sm">Longitudine
<i class="fa fa-sort float-right" aria-hidden="true"></i>
</th>
</tr>
</thead>
<tbody>
<?php
while($row = mysqli_fetch_assoc($query)){ ?>
<tr>
<td>
<!-- Material unchecked -->
<div class="form-check">
<input type="checkbox" name="impianto_id_campagna" class="form-check-input" value="<?php echo $row['id'] ;?>" id="<?php echo $row['id'] ;?>">
<label class="form-check-label" for="<?php echo $row['id'] ;?>"></label>
</div>
</td>
<td><?php echo $row['cimasa'] ;?></td>
<td><?php echo $row['proprietaria'] ;?></td>
<td><?php echo $row['concessionaria'] ;?></td>
<td><?php echo $row['city'] ;?></td>
<td><?php echo $row['lat'] ;?></td>
<td><?php echo $row['lng'] ;?></td>
</tr>
<?php } ?>
</tfoot>
</table>
<input class="btn btn-primary" name="submit" type="submit" value="Register..."><br>
</form>
</div>
</div>
It register only the last one selected product because you have the same name attribute for every checkbox. Set the name to impianto_id_campagna[] in order to return an array in your $_POST variable.
<input type="checkbox" name="impianto_id_campagna[]" class="form-check-input" value="<?php echo $row['id'] ;?>" id="<?php echo $row['id'] ;?>">
Then you loop all your checkbox values inserting one product at a time:
<?php
$id_campagna_cliente = $connessione->real_escape_string($_POST['id_campagna_cliente']);
$cliente_id_campagna = $connessione->real_escape_string($_POST['cliente_id_campagna']);
foreach ($_POST['impianto_id_campagna'] as $value)
{
$impianto_id_campagna = $connessione->real_escape_string($value);
$connessione->query("INSERT INTO campagne_cliente (
id_campagna_cliente,
cliente_id_campagna,
impianto_id_campagna)
VALUES (
'$id_campagna_cliente',
'$cliente_id_campagna',
'$impianto_id_campagna')");
$messaggio = "Registrazione Completata!";
}
Checkbox items are passed as an array. In order to get them in to the database, you have to loop through the array and act accordingly.
foreach($impianto_id_campagna as $row){
//Iterate through and do what you need to do with the data.
}