I have a daterange picker and it is fully working. However, I have a new target which is daterange with timepicker. But the thing is I don't know how to implement it like what I did on my daterange without timepicker. Is there any way where I can implement it? I have provided my codes below of my fully working daterange picker. I have provided also my screenshot of my current daterange and my target daterange with timepicker. Thank you in advance.
HTML:
<div class="img-fluid">
<div class="input-group">
From:
<input type="date" class="mr-4" id="from" name="from">
To:
<input type="date" id="to" name="to" style="margin-right:50px;">
</div>
</div>
<div class="tab-pane fade show active" id="custom-tabs-two-1" role="tabpanel" aria-labelledby="custom-tabs-two-1-tab">
<table id="testing" class="table-striped table table-head-fixed" style="min-width:1000px; width:100%;">
<thead class="" style="background-color: #404040; color: white;">
<tr>
<th scope="col"><i class="fas fa-list-ol mr-2"></i>Transaction ID</th>
<th scope="col"><i class="fas fa-list-ol mr-2"></i>Reference No.</th>
<th scope="col"><i class="far fa-calendar-alt mr-2"></i>Date Requested</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
Script & Ajax:
var save_method; //for save method string
var table;
var base_url = '<?php echo base_url();?>';
$(document).ready(function() {
//datatables
var table = $('#testing').DataTable({
dom: 'lBfrtip',
buttons: [
'print', 'csv', 'copy', 'excel', 'pdfHtml5'
],
"processing": false, //Feature control the processing indicator.
"serverSide": true, //Feature control DataTables' server-side processing mode.
"order": [], //Initial no order.
// Load data for the table's content from an Ajax source
"ajax": {
"url": "<?php echo site_url('controller/ajax_list')?>",
"type": "POST",
"data": function ( data ) {
data.from = $('#from').val();
data.to = $('#to').val();
},
},
//Set column definition initialization properties.
"columnDefs": [
{
"targets": [ 0 ], //first column
"orderable": false, //set not orderable
},
{
"targets": [ -1 ], //last column
"orderable": false, //set not orderable
},
],
});
setInterval( function () {
testing.ajax.reload(null,false);
}, 1000);
Controller:
public function ajax_list()
{
$list = $this->repo->admin();
$data = array();
$no = $_POST['start'];
foreach ($list as $person) {
$no++;
$row = array();
$row[] = $person->transID;
$row[] = $person->refNumber;
$row[] = $person->dateRequested;
$data[] = $row;
}
$output = array(
"draw" => $_POST['draw'],
"recordsTotal" => $this->repo->showing_pending(),
"recordsFiltered" => $this->repo->count_filtered(),
"data" => $data,
);
//output to json format
echo json_encode($output);
}
}
Model:
var $table = 'ca';
var $column_order = array(null,'transID','dateRequested','refNumber');
var $order = array('transID' => 'desc');
var $column_search = array('transID','dateRequested','refNumber');
//set column field database for datatable orderable //set column field database for datatable searchable just firstname , lastname , address are searchable var $order = array('id' => 'desc'); // default order
private function _get_datatables_query()
{
if($this->input->post('from')){
$this->db->where('dateCre >=', $this->input->post('from'));
$this->db->where('dateCre <=', $this->input->post('to'));
}
$this->db->from('ca');
$i = 0;
foreach ($this->column_search as $item)
{
if($_POST['search']['value'])
{
if($i===0) // first loop
{
$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 admin()
{
$this->_get_datatables_query();
if($_POST['length'] != -1)
$this->db->limit($_POST['length'], $_POST['start']);
$query = $this->db->get();
return $query->result();
}
public function showing_pending()
{
$this->db->from($this->table);
return $this->db->count_all_results();
}
function count_filtered()
{
$this->_get_datatables_query();
$query = $this->db->get();
return $query->num_rows();
}
}
What is your exact error? I think that you need to sanitize your post values before the query.
Change This:
$this->db->where('dateCre >=', $this->input->post('from'));
To this (please select the correct format in your case)
$from_date = DateTime::createFromFormat('d/m/Y h:m:s', $this->input->post('from'));
$this->db->where('dateCre >=', $from_date->format('Y-m-d h:m:s'));
Do it also with the "post('to')" value.
Related
Hello guys im trying to learn vue and im trying to use datatable from https://datatables.net/ and having a problem with my action button that im not able to get the id when the #viewModal is been triggered i hope someone can help me to get the id of each buttons thanks and here is my code TIA:
EmployeeDataTable Component :
<template>
<div class="card">
<div class="card-header">
<div class="card-title">Employee List</div>
</div>
<div class="card-body">
<div class="table-responsive">
<table
id="employee-table"
class="table-sm table-bordered table-hover text-center display"
width="100%"
>
<thead>
<tr>
<th class="pt-3 pb-3">#</th>
<th>Name</th>
<th>Address</th>
<th>Contact #</th>
<th>Department</th>
<th>Status</th>
<th>Actions</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
</div>
</div>
</template>
<script>
//For Datatable to work
import "datatables.net";
import EmployeeEdit from "./EmployeeEdit.vue";
export default {
name: "EmployeeList",
data() {
return {
employees: [],
};
},
mounted() {
this.getEmployeeLists();
},
components: {
"employee-edit": EmployeeEdit,
},
methods: {
getEmployeeLists() {
// INITIALIZE DATATABLE
$("#employee-table")
.DataTable({
//LOADING
// processing: true,
//AJAX
serverSide: true,
//DIRECTION
order: [[1, "desc"]],
//AJAX
ajax: {
url: "/api/getEmployeeLists",
dataList: "json",
type: "POST",
data: { _token: "{{csrf_token()}}" },
},
//TABLE COLUMNS SHOULD BE THE SAME IN CONTROLLER
columns: [
{ data: "#" },
{ data: "name" },
{ data: "address" },
{ data: "contact" },
{ data: "department" },
{ data: "status" },
{
data: "actions",
//allowing modification
createdCell(cell, cellData, rowData) {
let EmployeeListDataTableActions = Vue.extend(
require("./EmployeeListDataTableAction.vue").default
);
let instance = new EmployeeListDataTableActions().$mount();
$(cell).empty().append(instance.$el);
},
},
],
//View Count in Table
lengthMenu: [
[10, 25, 50, -1],
[10, 25, 50, "All"],
],
})
.columns();
},
beforeDestroy: function () {
$(this.$el).DataTable().destroy();
},
},
};
</script>
EmployeeDataTableAction Component :
<template>
<button class="btn btn-primary btn-sm" #click="viewModal" title="View Employee Details">
<i class="fa fa-eye"></i>
</button>
</template>
<script>
export default{
name: 'EmployeeListDataTableAction',
data: function() {
return {
}
},
mounted() {
},
methods: {
viewModal() {
var id = $(this.$el).closest('tr').find('input').val();
return false;
axios
.post(`/api/getEmployeeDetails/${id}`, {
id: id,
})
.then((response) => {
$("#edit-employee-modal").modal("show");
$(".myModalLabel").text(
response.data.name +
" - " +
response.data.department_name
);
state.commit("getEmployeeDetailsArray", response.data);
state.commit("getTransactionId", response.data.id);
})
.catch((response) => {
this.$toast.top("Something went wrong!");
});
},
},
}
</script>
Employee Controller for the DataTable :
public function employeeList(Request $request){
$all = Employee::getEmployeeTotal();
//total count of data
$total_data = $all;
//total filter
$total_filtered = $total_data;
//set_time_limit(seconds)
$limit = $request->input('length');
//start
$start = $request->input('start');
//order
// $order = $columns[$request->input('order.0.column')];
//direction
$dir = $request->input('order.0.dir');
$search_value = $request->input('search.value');
if (!empty($search_value)) {
$posts = Employee::getEmployeeNameSearch($search_value,$start, $limit, $dir);
$total_data = count($posts);
$total_filtered = $total_data;
}else{
if(empty($request->input('search.value')))
{
//if no search
$posts = Employee::getEmployeeList($start, $limit, $dir);
}
}
$data = array();
if(!empty($posts))
{
$counter = $start + 1;
foreach ($posts as $post)
{
$department = GlobalModel::getSingleDataTable('departments',$post->department_id);
$status = StatusController::checkStatus($post->status);
$nested_data['#'] = '<span style="font-size: 12px ; text-align: center;">'.$counter++.'</span>';
$nested_data['name'] = '<p style="text-align: center;">'.$post->name.'</p>';
$nested_data['address'] = '<p style="text-align: center;">'.$post->address.'</p>';
$nested_data['contact'] = '<p style="text-align: center;">'.$post->contact.'</p>';
$nested_data['department'] = '<p style="text-align: center;">'.$department->name.'</p>';
$nested_data['status'] = '<p style="text-align: center;">'.$status.'</p>';
$nested_data['actions'] = '';
$data[] = $nested_data;
}
}
$json_data=array(
"draw" => intval($request->input('draw')),
"recordsTotal" => intval($total_data),
"recordsFiltered" => intval($total_filtered),
"data" => $data
);
return response()->json($json_data);
}
In the second line of your viewModal() function, you are placing a return false; statement. "The return statement ends function execution and specifies a value to be returned to the function caller." From Mozilla docs. That's why the API call is never executing.
I have a target where I need to filter the data using daterange with time picker. The thing is I need to show the result of my filtered data based on what I selected on the said daterange with time picker I have provided my codes below and my target. Thank you so much in advance.
Views:
<div class="card-body table-responsive py-3 px-3">
<input type="text" id="demo" name="daterange" value="06/05/2021 - 06/06/2021" style="width:350px;">
<button class="btn btn-success float-right" onclick="add_person()" data-dismiss="modal"><i class="glyphicon glyphicon-plus"></i> Add Person</button>
<table id="table_account" class="table table-bordered table-hover" cellspacing="0">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Username</th>
<th>Email</th>
<th>Mobile</th>
<th>Role</th>
<th>Status </th>
<!-- <th>File </th> -->
<th>Added By</th>
<th>Date Created</th>
<th>Date Updated</th>
<th>Updated By</th>
<th style="width:100x;">Action</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</script>
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Username</th>
<th>Email</th>
<th>Mobile</th>
<th>Role</th>
<th>Status </th>
<th>Added By</th>
<th>Date Created</th>
<th>Date Updated</th>
<th>Updated By</th>
<th style="width:100x;">Action</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
Ajax:
<script>
// first, put this at the top of your JS code.
let dateParams = {}
// update this with setting dataParams
$('#demo').daterangepicker({
"timePicker": true,
"timePicker24Hour": true,
"startDate": "06/05/2021",
"endDate": "06/06/2021",
locale: {
format: 'M/DD/YYYY hh:mm A'
}
}, function(start, end, label) {
// set the dateParam obj
dateParams = {
start: start.format('YYYY-MM-DD hh:mm'),
end: end.format('YYYY-MM-DD hh:mm')
}
console.log('New date range selected: ' + start.format('YYYY-MM-DD hh:mm') + ' to ' + end.format('YYYY-MM-DD hh:mm') + ' (predefined range: ' + start + + end +')');
});
$(document).ready(function() {
//datatables
table = $('#table_account').DataTable({
dom: 'lBfrtip',
buttons: [
'print', 'csv', 'copy', 'excel', 'pdfHtml5'
],
"processing": false, //Feature control the processing indicator.
"serverSide": true, //Feature control DataTables' server-side processing mode.
"order": [], //Initial no order.
// Load data for the table's content from an Ajax source
"ajax": {
"url": "<?php echo site_url('profile/ajax_list')?>",
"type": "POST",
"data": function (dateParams) {
return $.extend( { "start": dateParams.start,
"end": dateParams.end,}, dateParams, {
});
},
},
//Set column definition initialization properties.
"columnDefs": [
{
"targets": [ 0 ], //first column
"orderable": false, //set not orderable
},
{
"targets": [ -1 ], //last column
"orderable": false, //set not orderable
},
],
});
});
setInterval( function () {
table.ajax.reload(null,false);
}, 1000);
</script>
Controller:
public function ajax_list()
{
$list = $this->profiles->get_datatables();
$data = array();
$no = $_POST['start'];
foreach ($list as $person) {
$no++;
$row = array();
$row[] = $person->firstname;
$row[] = $person->lastname;
$row[] = $person->username;
$row[] = $person->email;
$row[] = $person->mobile;
$row[] = $person->role;
$row[] = $person->status;
$row[] = $person->addedBy;
$row[] = $person->dateCreated;
$row[] = $person->updatedBy;
$row[] = $person->dateUpdated;
//add html for action
$row[] = '<a class="btn btn-sm btn-primary" href="javascript:void(0)" title="Edit" onclick="edit_person('."'".$person->userID."'".')"><i class="glyphicon glyphicon-pencil"></i> Edit</a>';
$data[] = $row;
}
$output = array(
"draw" => $_POST['draw'],
"recordsTotal" => $this->profiles->count_all(),
"recordsFiltered" => $this->profiles->count_filtered(),
"data" => $data,
);
//output to json format
echo json_encode($output);
}
Model:
var $table = 'users';
var $column_order = array(null,'userID','firstname','lastname','username','email','mobile','addedBy','dateCreated');
var $order = array('userID' => 'desc');
var $column_search = array('email','firstname','lastname','username','email','mobile','dateCreated');
//set column field database for datatable orderable //set column field database for datatable searchable just firstname , lastname , address are searchable var $order = array('id' => 'desc'); // default order
private function _get_datatables_query()
{
if($this->input->post('daterange')){
$this->db->where('dateCreated >=', $this->input->post('start'));
$this->db->where('dateCreated <=', $this->input->post('end'));
}
// $this->input->post('start'); // YYYY-mm-dd
// $this->input->post('end'); // YYYY-mm-dd
$this->db->from($this->table);
$i = 0;
foreach ($this->column_search as $item) // loop column
{
if($_POST['search']['value']) // if datatable send POST for search
{
if($i===0) // first loop
{
$this->db->group_start(); // open bracket. query Where with OR clause better with bracket. because maybe can combine with other WHERE with AND.
$this->db->like($item, $_POST['search']['value']);
}
else
{
$this->db->or_like($item, $_POST['search']['value']);
}
if(count($this->column_search) - 1 == $i) //last loop
$this->db->group_end(); //close bracket
}
$i++;
}
if(isset($_POST['order'])) // here order processing
{
$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();
}
To connect the calendar with the data output table, edit your daterangepicker initialization:
// first, put this at the top of your JS code.
let dateParams = {}
// update this with setting dataParams
$('#demo').daterangepicker({
"timePicker": true,
"timePicker24Hour": true,
"startDate": "06/05/2021",
"endDate": "06/06/2021",
locale: {
format: 'M/DD hh:mm A'
}
}, function(start, end, label) {
// set the dateParam obj
dataParams = {
start: start.format('YYYY-MM-DD'),
end: end.format('YYYY-MM-DD')
}
// reload the table
table.ajax.reload();
//console.log('New date range selected: ' + start.format('YYYY-MM-DD') + ' to ' + end.format('YYYY-MM-DD') + ' (predefined range: ' + label + ')');
});
Over in your DataTable() setup change your ajax to pass the start and end dates
"ajax": {
"url": "<?php echo site_url('profile/ajax_list')?>",
"type": "POST",
"data": function ( d ) {
// add this
return $.extend( {}, d, {
"start": dataParams.start,
"end": dataParams.end
});
// could also be written: return $.extend( {}, d, dataParams);
}
}
Finally, you'll need to pick this up in your CI app so you can search you DB.
$this->input->post('start'); // YYYY-mm-dd
$this->input->post('end'); // YYYY-mm-dd
Then this is just a nit. Please move <table id="table_account" class="table table-bordered table-hover" cellspacing="0"> to right above the first <thead>. Right now there is the datepicker element in between them. Might not matter, but it should be fixed.
https://datatables.net/reference/option/ajax
I want to show a data controller to view using ajax and I have already shown a data controller to view on the chart bar without ajax I need to get data on the chart bar using ajax but I don't have an idea how to show data on chart bar using ajax.
I don't have that good experience in JSON/AJAX/Laravel, I'm a beginner.
Controller
public function index()
{
$manager_hourlog = Hourlog::with('project', "user")->get()-
>groupBy('project.name');
$projects = [];
$totals = [];
foreach ($manager_hourlog as $key => $val) {
$projects[] = $key;
}
foreach ($manager_hourlog as $key2 => $val) {
$minutes = $val->sum('hour_work');
$totals[] = round($minutes / 60, 1);
}
$users = User::where("status", 1)->get();
$data = [
// manager report
'manager_projects' => $projects,
'totals' => $totals,
"manager_hourlog" => $manager_hourlog,
"auth" => $auth,
];
return response()->json(['data' => $data]);
return view('cms.dashboard', $data);
}
Script
<script>
// Employee report script
var colors = ["#1abc9c", "#2ecc71", "#3498db",
"#9b59b6", "#34495e", "#16a085", "#27ae60"];
#if ($auth->user_type != 1)
// manager report script
var managerchartbar = {
labels: {!! json_encode($manager_projects) !!},
datasets: [
#foreach($users as $user)
{
label: {!! json_encode($user->name) !!},
backgroundColor: colors[Math.floor(Math.random() * colors.length)],
// data: [300,200,500,700]
data: [
#foreach($manager_hourlog as $hourlog)
{{$hourlog->where("user_id", $user->id)->sum("hour_work") / 60}},
#endforeach
]
},
#endforeach
]
};
var ctx = document.getElementById('manager').getContext('2d');
window.myBar = new Chart(ctx, {
type: 'bar',
data: managerchartbar,
options: {
title: {
display: true,
text: 'Employees Report chart'
},
tooltips: {
mode: 'index',
intersect: false
},
responsive: true,
scales: {
xAxes: [{
stacked: true,
}],
yAxes: [{
stacked: true
}]
}
}
});
#endif
ajax
$.ajax({
type: 'GET',
url: '{{url("/dashboard")}}',
data: {
data: data
},
success: function(data){
console.log(data.data);
},
error: function(xhr){
console.log(xhr.responseText);
}
});
</script>
Html VIew
<div class="col-md-12">
<div class="card-box">
<div class="container-fluid">
<canvas id="manager" height="100">
</canvas>
</div>
</br>
</div>
</div>
Route
Route::get('/dashboard',
'DashboardController#index')->name('dashboard');
I can print the data out but data is not displayed in the table.
I'm trying to use Datatable to display the data.
Here are error messages:
DataTables warning: table id=example - Invalid JSON response. For more information about this error, please see http://datatables.net/tn/1
model
function allposts_count()
{
$query = $this
->db
->get('books');
return $query->num_rows();
}
function allposts($limit,$start,$col,$dir)
{
$query = $this
->db
->limit($limit,$start)
->order_by($col,$dir)
->get('books');
if($query->num_rows()>0)
{
return $query->result();
}
else
{
return null;
}
}
controller
function Book()
{
$columns = array(
0 =>'id',
1 =>'title',
);
$limit = $this->input->post('length');
$start = $this->input->post('start');
$columns=$this->input->post('order')[0]['column'];
$order = $columns;
$dir = $this->input->post('order')[0]['dir'];
$totalData = $this->user_model->allposts_count();
$totalFiltered = $totalData;
if(empty($this->input->post('search')['value']))
{
$posts = $this->user_model->allposts($limit,$start,$order,$dir);
}
else {
$search = $this->input->post('search')['value'];
$posts = $this->user_model->posts_search($limit,$start,$search,$order,$dir);
$totalFiltered = $this->user_model->posts_search_count($search);
}
$data = array();
if(!empty($posts))
{
foreach ($posts as $post)
{
$nestedData['id'] = $post->book_id;
$nestedData['title'] = $post->book_title;
$data[] = $nestedData;
}
}
$json_data = array(
"draw" => intval($this->input->post('draw')),
"recordsTotal" => intval($totalData),
"recordsFiltered" => intval($totalFiltered),
"data" => $data
);
$json = json_encode($json_data);
echo $json;
$this->load->view('templates/header');
$this->load->view('users/Book',$json);
$this->load->view('templates/footer');
}
view
<div class="container">
<h1>Server Side Process Datatable</h1>
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
</tr>
</thead>
<tfoot>
<tr>
<th>ID</th>
<th>Name</th>
</tr>
</tfoot>
</table>
<!--create modal dialog for display detail info for edit on button cell click-->
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<div id="content-data"></div>
</div>
</div>
</div>
<script>
$(document).ready(function(){
var dataTable=$('#example').DataTable({
"processing": true,
"serverSide":true,
"ajax":{
"url": "<?php echo base_url('users/Book') ?>",
"dataType": "json",
"type": "POST",
"data":{ '<?php echo $this->security->get_csrf_token_name(); ?>' : '<?php echo $this->security->get_csrf_hash(); ?>' }
},
"columns": [
{ "data": "book_id" },
{ "data": "book_title" },
]
});
});
</script>
datatables expects a pure json response. if you followed the debugging steps in the link you posted you would have seen that your response also contains a view.
here you have json then a view:
$json = json_encode($json_data);
echo $json;
$this->load->view('templates/header');
$this->load->view('users/Book',$json);
$this->load->view('templates/footer');
remove the views and/or move the json stuff to another url. then update "url": "<?php echo base_url('users/Book') ?>", to the new url.
you should echo $data to show data in table #example.
<table id="example" cellpadding="0" cellspacing="0">
<thead><tr>
<th>ID</th>
<th>Name</th>
</tr></thead>
<tbody>
<!-- rows will go here -->
</tbody>
</table>
And in javascript
$("#example tbody").html(someHtmlString);
You dont have tbody to put return query in your code.
And debug to check if the data is valid or not.
I am trying to update some calendar data to database. But each time I update it updates my day column it updates with 18<span class="label label-danger" xss=removed>Notice</span> It should only update day column with number 18
I am not sure why the $this->input->post('day') has added the span information.
Here is my var dump.
array (size=2)
17 => string 'Event 17-12-15' (length=14)
'18<span class="label label-danger" xss=removed>Notice</span>' => string '26' (length=2)
Quesions:
How is it possible to only update day column with number and not with span?
What could be causing it to have span updated with number?
Tried:
$this->input->post('day', TRUE)
$this->input->post('day', FALSE)
Controller
Note: I am using models functions on controller just for testing
<?php
class Calendar extends MX_Controller {
public function __construct() {
parent::__construct();
$this->load->model('dashboard/model_calendar');
$this->load->library('calendar');
}
public function index() {
if ($this->uri->segment(3) == FALSE) {
$year = date('Y');
} else {
$year = $this->uri->segment(3);
}
$data['year'] = $year;
if ($this->uri->segment(4) == FALSE) {
$month = date('m');
} else {
$month = $this->uri->segment(4);
}
$data['month'] = $month;
var_dump($this->get_calendar_data($year, $month));
$prefs = array(
'start_day' => 'monday',
'show_next_prev' => true,
'day_type' => 'long',
'next_prev_url' => base_url('dashboard/calendar')
);
$prefs['template'] = '
{table_open}<table border="0" cellpadding="0" cellspacing="0" class="table table-striped table-bordered calendar">{/table_open}
{heading_row_start}<tr>{/heading_row_start}
{heading_previous_cell}<th><i class="fa fa-chevron-left fa-2x "></i></th>{/heading_previous_cell}
{heading_title_cell}<th class="text-center" colspan="{colspan}">{heading}</th>{/heading_title_cell}
{heading_next_cell}<th class="text-right"><i class="fa fa-chevron-right fa-2x"></i></th>{/heading_next_cell}
{heading_row_end}</tr>{/heading_row_end}
{week_row_start}<tr>{/week_row_start}
{week_day_cell}<td>{week_day}</td>{/week_day_cell}
{week_row_end}</tr>{/week_row_end}
{cal_row_start}<tr class="days">{/cal_row_start}
{cal_cell_start}<td class="day">{/cal_cell_start}
{cal_cell_content}
<div class="day_num">{day}<span class="label label-danger" style="margin-left: 10px;">Notice</span></div>
<div class="content">{content}</div>
{/cal_cell_content}
{cal_cell_content_today}
<div class="day_num highlight">{day}</div>
<div class="content">{content}</div>
{/cal_cell_content_today}
{cal_cell_no_content}<div class="day_num">{day}</div>{/cal_cell_no_content}
{cal_cell_no_content_today}<div class="day_num highlight">{day} <span class="label label-success">Current Day</span></div>{/cal_cell_no_content_today}
{cal_cell_blank} {/cal_cell_blank}
{cal_cell_end}</td>{/cal_cell_end}
{cal_row_end}</tr>{/cal_row_end}
{table_close}</table>{/table_close}
';
$this->calendar->initialize($prefs);
if ($this->input->post('day')) {
$this->update_calendar_event($year, $month);
}
$data = $this->get_calendar_data($year, $month);
$data['calendar'] = $this->calendar->generate($year, $month, $data);
$this->load->view('dashboard/calender_view', $data);
}
public function update_calendar_event($year, $month) {
$date = $year .'-'. $month .'-'. $this->input->post('day');
$calendar = array(
'year' => $year,
'month' => $month,
'day' => $this->input->post('day', TRUE),
'data' => $this->input->post('data')
);
$this->db->where('date', $date);
$this->db->update('calendar', $calendar);
}
public function get_calendar_data($year, $month) {
$cell_data = array();
$this->db->select('*');
$this->db->from('calendar');
$this->db->where('year', $year);
$this->db->where('month', $month);
$query = $this->db->get();
foreach ($query->result() as $result) {
$cell_data[$result->day] = $result->data;
}
return $cell_data;
}
public function check_calendar_event($year, $month, $day) {
$date = $year .'-'. $month .'-'. $day;
$this->db->select('year, month, day');
$this->db->from('calendar');
$this->db->where('date', $date);
$results = $this->db->count_all_results();
return $results;
}
}
View
<div class="panel panel-default">
<div class="panel-heading">
<h1 class="panel-title">Calendar</h1>
</div>
<div class="panel-body">
<?php echo $calendar;?>
</div>
</div>
<script type="text/javascript">
$(document).ready(function() {
$('.calendar .day').click(function() {
day_num = $(this).find('.day_num').html();
day_data = prompt('Enter Event', $(this).find('.content').html());
if (day_data != null) {
$.ajax({
url: window.location,
type: 'POST',
data: {
day: day_num,
data: day_data
},
success: function(msg) {
location.reload();
}
});
}
});
});
</script>
There could be couple of options why you are having this problem. to find out which one start by checking the does day_num passing to your Controller? do this:
<script type="text/javascript">
$(document).ready(function() {
$('.calendar .day').click(function() {
day_num = $(this).find('.day_num').html();
day_data = prompt('Enter Event', $(this).find('.content').html());
if (day_data != null) {
$.ajax({
url: window.location,
type: 'POST',
data: {
day: day_num,
data: day_data
},
success: function(msg) {
//location.reload(); turn off the reload for now.
alert(day_num); //what does this alert show?
}
});
}
});
});
And leave a comment on what does the alert show you? the number 18 or the whole HTML so i know how to help you..