I tried to submit dynamic data to jscript and render the data using php from api url, but how can I pass the pagination number to the datable jscript and letting php to define the pageindex dynamically?
I tried to pass the value into the function, it will totally reload the ajax table for me and stay back at page number 1 instead of page number 2.
the api returns:
{
"data": [...],
"pageindex": 1,
"totalrecord": 708,
"totalpage": 71
}
My Form jquery:
$('.form-filter form').on('submit', function(e) {
e.preventDefault();
const start = $('.form-filter [name=start]').val();
const end = $('.form-filter [name=end]').val();
const type = $('.form-filter [name=type]').val();
const status = $('.form-filter [name=status]').val();
if (this.checkValidity() !== false) {
action_handle('fire_search');
var datetime = timezone(start, end);
paymentTable(datetime[0], datetime[1], type, status);
}
});
The datatable jscript:
function paymentTable(from, to, type, status) {
const paymentTable = $('#table').DataTable({
ajax: {
type : "POST",
url: "/api/somethinng/history",
data: {"start": from, "end": to, "type": type, "status": status},
dataSrc: function(json) {
if(json == "no data") {
return [];
} else {
return json.data;
}
}
},
responsive: {
details: {
renderer: $.fn.dataTable.Responsive.renderer.tableAll({
tableClass: 'ui display nowrap table-sm table-bordered'
})
}
},
processing: true,
serverSide: true,
deferRender: true,
destroy: true,
order: [[0,"desc"]],
}
});
paymentTable.draw();
}
My PHP function to get the data from api:
public function api_history() {
$raw = $this->balance_model->data_source([
'type' => 1,
'status' => 1,
'fromdate' => '2020-10-01',
'todate'=> '2020-10-05',
'pageindex' => 1,
'rowperpage' => 1000
]);
if( $raw['code'] == 1 && $raw['data'] != [] ):
asort($raw['data']);
$data = [];
foreach( $raw['data'] as $ph ):
$row = [];
$row[] = $ph['date'];
$row[] = $ph['id'];
$row[] = $ph['amount'];
$data[] = $row;
endforeach;
echo json_encode([
'data' => $data
'draw' => (int)$_POST['draw'],
'recordsTotal' => $raw['totalRecord'],
'recordsFiltered' => $raw['totalRecord']
]);
else:
echo json_encode(['no data']);
endif;
}
Related
I've been having trouble with Full Calendar. I already tried different approaches but to no avail. The json response doesn't shows up in the calendar.
View:
<div class="col-lg-12 col-md-12">
<div id="calendar">
</div>
</div>
Controller:
public function calendar(Request $request){
if($request->ajax()){
$data= Table::where('id',Auth::user()->id)
->where('DateFrom','>',$request->start)
->where('DateTo','<',$request->end)
->get();
return response()->json($data);
}
}
Route:
Route::get('/calendar', [CalendarController::class, 'calendar'])->name('calendar');
Script (mix):
$('#calendar').fullCalendar({
events: 'calendar',
eventColor: '#378006',
displayEventTime: true,
eventRender: function (event, element, view) {
if (event.allDay === 'true') {
event.allDay = true;
} else {
event.allDay = false;
}
},
selectable: true,
selectHelper: true,
})
There are no errors, the data is also being fetched but the problem is the calendar can't render it. May I ask is there any problem with this? Do I need to actually create a partial view for this and then include it to another blade file?
The problem was that I was fetching a different type of date which doesn't match up with the dates from the Fullcalendar. So to show/highlight those dates I did this.
Controller:
public function calendar(Request $request){
if($request->ajax()){
$event= Table::where('id',Auth::user()->id)
->where('DateFrom','>',date('Y-m-d',$request->start)) //converts date
->where('DateTo','<',date('Y-m-d',$request->end)) //converts date
->get();
$data = [];
foreach($event as $row){
$data[] = [
'title' => $row->title,
'start' => date(DATE_ISO8601,strtotime($row->DateFrom)),
'end' => date(DATE_ISO8601,strtotime($row->DateTo))
];
}
return response()->json(collect($data));
}
return view('partials._calendar-details',compact('data'));
}
and then for my script:
$('#calendar').fullCalendar({
// events: 'calendar',
eventColor: '#378006',
displayEventTime: false,
eventSources: [
{
events: function(start, end, timezone, callback ){
$.ajax({
url: '/calendar',
type: 'GET',
data: {
// our hypothetical feed requires UNIX timestamps
start: start.unix(),
end: end.unix()
},
dataType: 'json',
success: function(res) {
var events = [];
for (var i = 0; i < res.length; i++){
console.log(res[0].title);
events.push({
title: res[0].title,
start: res[0].start,
end: res[0].end
});
}
callback(events);
},
});
},
color: 'darkblue', // an option!
textColor: 'white', // an option!
}
],
eventRender: function (event, element, view) {
if (event.allDay === 'true') {
event.allDay = true;
} else {
event.allDay = false;
}
},
selectable: true,
selectHelper: true,
})
I create an edit page to edit the data. After the user edits the form. The form should be saved. But in my case I can't save the form it's showing error.
I facing this error.
ReminderComponent.vue
<script>
import Vue from 'vue'
import axios from 'axios'
import VueAxios from 'vue-axios'
import MarkdownIt from 'markdown-it'
import ClassicEditor from '#ckeditor/ckeditor5-build-classic';
var msg_editor;
Vue.use(VueAxios, axios);
const md = new MarkdownIt({
linkify: true
})
export default {
props: ['email_creation_link', 'email_index_route', 'email_edit_route','conditions','modules','mailtemplates'],
components: {
},
data() {
return {
template:
{
subject: '',
message: '' ,
days: '',
condition_id: 1,
},
options:[
{
display:'Client Name',
actual:'Client name'
},
{
display:'Joined Date',
actual:'Joined date'
},
{
display:'Module Name',
actual:'Module name'
},
{
display:'Last Seen',
actual:'Last seen'
},
],
showName: false,
}
},
mounted(){
var self = this;
ClassicEditor
.create(document.querySelector( "#msg"),
{
})
.then(editor => {
msg_editor = editor;
editor.model.document.on( 'change:data', () => {
self.template.message = msg_editor.getData();
});
})
.catch(error => {
console.error(error);
})
if (this.mailtemplates) {
this.template=this.mailtemplates;
}
},
methods: {
//Drag items
dragstart: function(item, e){
this.draggingItem = item;
e.dataTransfer.setData('text/plain', item.actual);
},
dragend: function(item,e) {
e.target.style.opacity = 1;
},
dragenter: function(item, e) {
this.draggingItem = item;
},
//content
replaceVariables(input)
{
let updated = input
return updated
},
//hidecontent
showHide: function(e)
{
console.log("Show "+e.target.value+ " fields")
this.showName = e.target.value !== ''
},
fetch()
{
//request data
axios.get(this.email_index_route,this.template)
.then((res) => {
this.template = res.data.template;
})
**axios.get(this.email_edit_route,this.mailtemplates)
.then((res) => {
this.mailtemplates = res.data.template;
})**
},
save()
{
//save data to db
axios.post(this.email_index_route, this.template)
.then((res) => {
alert('Mail sent successfull!')
})
**axios.post(this.email_edit_route, this.mailtemplates)
.then((res) => {
alert('Mail sent successfull!')
})**
},
addToMail: function(type, text)
{
if (type == 'message') {
this.template.message += text;
msg_editor.setData(this.template.message);
}
},
//user name replace
replaceVariables() {
return this.replaceVariables(this.options || '')
},
}
}
</script>
I think this area causing problem but i can't find the solution.
axios.get(this.email_edit_route,this.mailtemplates)
.then((res) => {
this.mailtemplates = res.data.template;
})
axios.post(this.email_edit_route, this.mailtemplates)
.then((res) => {
alert('Mail sent successfull!')
})
route file
Route::get('api/email/create', ['as' => 'email.create', 'uses' => 'Havence\AutoMailController#create']);
Route::get('automail/mail', 'Havence\AutoMailController#mail');
Route::get('automail/index',['as'=>'email.index','uses' => 'Havence\AutoMailController#index']);
Route::post('automail/edit/{id}',['as'=>'email.edit','uses' => 'Havence\AutoMailController#edit']);
Route::get('automail/delete',['as'=>'email.delete','uses' => 'Havence\AutoMailController#destroy']);
I kept searching for this but couldn't find an answer that will make this clear.
Thanks!
As per your error and your route file you are using POST method on your edit page but your edit method accepts only GET method that is why you are getting this error.
I'm getting this error
I am using Canvasjs Charts to do my graphing from PHP / MySQL. Everything works as expected except for the creating of my JSON file.
Canvasjs requires the JSON file to look as follow:
callback({
"dps":
[{"division":"Xaxis VALUE","units":Yaxis VALUE}]
})
However, when creating my JSON file it is
[{"division":"Xaxis VALUE","units":Yaxis VALUE}]
All I want to know is how do I add the opening tag and closing tag in the sjon file from my script.
Here is the last part of my code that creates the JSON file:
$output_data= array();
while($row = mysqli_fetch_array($result))
{
$output_data[] = array(
'division' => $row["division"],
'units' => $row["units"]
);
}
return json_encode($output_data, JSON_NUMERIC_CHECK);
echo json_encode($output_data, JSON_NUMERIC_CHECK);
}
$file_name = 'myresult2'.'.json';
if(file_put_contents($file_name, get_data()))
{
echo $file_name. 'file created';
}
else
{
echo 'Error';
}
?>
Additional Data:
This is the code that generates the graph.
<script>
var chart = null;
var dataPoints = [];
window.onload = function() {
chart = new CanvasJS.Chart("chartContainer", {
animationEnabled: true,
theme: "light",
title: {
text: "Graph Header"
},
axisY: {
title: "% Verified",
titleFontSize: 12,
labelFontSize: 12,
valueFormatString: "#.##%"
},
axisX: {
title: "Division",
titleFontSize: 12,
labelFontSize: 12
},
data: [{
type: "column",
yValueFormatString: "#.##%",
dataPoints: dataPoints
}]
});
$.getJSON("myresult.json?callback=?", callback);
}
function callback(data) {
for (var i = 0; i < data.dps.length; i++) {
dataPoints.push({
label: data.dps[i].division,
y: data.dps[i].units
});
}
chart.render();
}
</script>
Please try
// change this
$output_data[] = array(
// to this
$output_data['dps'][] = array(
What you need to do is enclose you created array in a new array with a key named dps.
So after your while loop you should do something like this
$json_data['dps']=$output_data;
return json_encode($json_data, JSON_NUMERIC_CHECK);
I am having problems while trying to show info from a Json to an alert, this is my code.
function check_values_chbx(){
var pre_insc = [];
}).done(function(response){
for(i=0; i<response.length; i++){
pre_insc[i] = response[0]['personas'][i]['name']+" "+response[0]['personas'][i]['ap_pat']+" "+response[0]['personas'][i]['ap_mat'];
}
alert(pre_insc[1]);
swal({
title: "Detalles de inscripcion",
text: "Participantes que quedaran inscritos: \n\n"+pre_insc.join('\n')+"\n\nCategoria:",
buttons: true,
dangerMode: false,
}).then((willDelete) => {
if (willDelete) {
swal("Participantes registrados con exito, mucha suerte!", {
icon: "success",
});
}else {
location.reload();
}
});
});
}
And this is my JSON
[
{
"personas": [
{
"name": "Jessica",
"ap_pat": "BocaNegra",
"ap_mat": "Garcia"
},
{
"name": "Fernando",
"ap_pat": "Soto",
"ap_mat": "Olivas"
}
],
"evento": [
{
"name": "Carrera larga"
}
],
"categoria": [
{
"name": "Juvenil"
}
]
}
]
I need to print each name like:
swal("name1\n"+name2\n"+etc").
Please if someone could help me it will be very helpful, have a nice day.
You can use the below script which recursively iterates a json object if it finds an array or Object until it finds the text for the given property and then print them all if the property name is name with \n separator, you can add the following inside your script file and pass it the response that you are receiving and use the returned names with your sweetAlert, just make sure you pass the response to the function like below
names = jsonParser.getNames(response[0]);
Add the below in you script
var jsonParser = {
isObject: function (property) {
return property && {}.toString.call(property) === '[object Object]';
},
isArray: function (property) {
return property && {}.toString.call(property) === '[object Array]';
},
getNames: function (errors) {
var data = "";
for (let message in errors) {
var errorSet = errors;
if (errorSet.hasOwnProperty(message)) {
if (jsonParser.isArray(errorSet[message]) || jsonParser.isObject(
errorSet[message])) {
data += jsonParser.getNames(errors[message]);
} else if (message == 'name') {
data += errorSet[message] + "\n";
}
}
}
return data;
}
};
An example to read the names from your given response is given below.
var jsonParser = {
isObject: function(property) {
return property && {}.toString.call(property) === '[object Object]';
},
isArray: function(property) {
return property && {}.toString.call(property) === '[object Array]';
},
convertToString: function(errors) {
var data = "";
for (let message in errors) {
var errorSet = errors;
if (errorSet.hasOwnProperty(message)) {
if (jsonParser.isArray(errorSet[message]) || jsonParser.isObject(
errorSet[message])) {
data += jsonParser.convertToString(errors[message]);
} else if (message == 'name') {
data += errorSet[message] + "\n";
}
}
}
return data;
}
};
var response = [{
"personas": [{
"name": "Jessica",
"ap_pat": "BocaNegra",
"ap_mat": "Garcia"
},
{
"name": "Fernando",
"ap_pat": "Soto",
"ap_mat": "Olivas"
}
],
"evento": [{
"name": "Carrera larga"
}],
"categoria": [{
"name": "Juvenil"
}]
}];
var names = '';
names = jsonParser.convertToString(response[0]);
console.log(names);
Your final script should look like
function check_values_chbx(){
var pre_insc = [];
}).done(function (response) {
var names = jsonParser.getNames(response[0]);
swal({
title: "Detalles de inscripcion",
text: "Participantes que quedaran inscritos: \n\n" + names +
"\n\nCategoria:",
buttons: true,
dangerMode: false,
}).then((willDelete) => {
if (willDelete) {
swal("Participantes registrados con exito, mucha suerte!", {
icon: "success",
});
} else {
location.reload();
}
});
});
Hope this helps you out
I am trying to display search results into a table using DataTables. I am getting search results into JSON and validated also against valid JSON, but I get this DataTables warning:
table id=volunteer_result - Invalid JSON response.
For more information about this error, please see http://datatables.net/tn/1.
I have used below codes :
views: searchdemo.php
<div class="form-group">
<button id="search_demo" class="btn btn-form">Search</button>
</div>
<div id="demo_result_div" class="table-responsive" style="background-color:#fff;">
<table id="demo_result" class="table table-bordered table-striped">
<thead>
<tr>
<th>Name</th>
<th>Role</th>
</tr>
</thead>
</table>
</div>
js: searchdemo.js
var table;
$('#search_demo').click(function () {
//datatables
table = $('#demo_result').DataTable({
"processing": true, //Feature control the processing indicator.
"serverSide": true, //Feature control DataTables' servermside processing mode.
//"order": [], //Initial no order.
"iDisplayLength" : 10,
// Load data for the table's content from an Ajax source
"ajax": {
"url": "<?php echo site_url('/demo/searchdemo')?>",
"type": "POST",
"dataType": "json",
"dataSrc": function (jsonData) {
return jsonData.data;
}
},
//Set column definition initialisation properties.
"columnDefs": [
{
"targets": [ 0 ], //first column / numbering column
"orderable": false, //set not orderable
},
],
});
});
controller:Demo.php
class Demo extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->model('demo/Demo_model');
}
public function index() {
}
public function searchdemo() {
$data['branch_list'] = $this->Demo_model->get_company_branches();
// set form validation rules
$this->form_validation->set_rules('branch', 'Branch', 'trim|required');
// submit
if ($this->form_validation->run() == FALSE) {
// validation failed, send validation errors to the view
$data['branch_list'] = $this->Demo_model->get_company_branches();
$this->load->view('templates/header');
$this->load->view('demo/searchdemo',$data);
$this->load->view('templates/footer');
} else {
// set variables from the form
$formdata = array(
'branch_id' => $this->input->post('branch'),
'length' => intval($this->input->post('length')),
'start' => intval($this->input->post('start')),
'order' => $this->input->post('order')
);
$users_list = $this->Demo_model->get_user_details($formdata);
if(!empty($users_list )){
$data = array();
foreach ($users_list as $user) {
$row = array();
$row['name'] = $user->name;
$row['role'] = $user->role;
$data[] = $row;
}
}
}
$output = array(
"draw" => intval($this->input->post('draw')),
"recordsTotal" => $this->Demo_model->count_all_active($formdata),
"recordsFiltered" => $this->Demo_model->count_filtered($formdata),
"data" => $data
);
//output to json format
echo json_encode($output);
}
}
model:Demo_model.php
class Demo_model extends CI_Model {
var $table = "users u";
var $select_column = array("u.id", "u.name", "ur.role");
var $column_order = array(null, "u.name","ur.role");
var $order = array('u.name' => 'asc'); // default order
function make_query($formdata) {
if($formdata['branch_id']) {
$this->db->select($this->select_column);
$this->db->from($this->table);
$this->db->where('u.active','yes');
$this->db->where('u.branch_id',$formdata['branch_id']);
$this->db->join('user_role ur','u.role_id=ur.id');
}
if(isset($_POST['order'])) { // here order processing
$this->db->order_by($this->column_order[$formdata['order']['0']['column']], $formdata['order']['0']['dir']);
}
else if(isset($this->order)) {
$order = $this->order;
$this->db->order_by(key($order), $order[key($order)]);
}
}
function get_user_details($formdata){
$this->make_query($formdata);
if(isset($formdata['length']) && $formdata['length'] < 1) {
$formdata['length']= '10';
} else {
$formdata['length']= $formdata['length'];
}
if(isset($formdata['start']) && $formdata['start'] > 1) {
$formdata['start']= $formdata['start'];
}
$this->db->limit($formdata['length'], $formdata['start']);
$query = $this->db->get();
return $query->result();
}
}
When I select a branch from the dropdown and click on Search button, it just returns the below JSON into the web browser instead of displaying results into search page table.
{
"draw": 0,
"recordsTotal": 2000,
"recordsFiltered": 2,
"data": [
{
"name": "Raman",
"role": "manager"
},
{
"name": "Maharaja",
"role": "admin"
}
]
}
I referred this link https://www.phpflow.com/php/server-side-datatable-sorting-searching-pagination-using-codeigniter-ii/
I have tried the many help URL for data table invalid JSON response but didn't get any luck.
You need to define data source for each column using columns.data option.
Change your initialization code as shown below:
var table = $('#demo_result').DataTable({
"processing": true,
"serverSide": true,
"ajax": {
"url": "<?php echo site_url('/demo/searchdemo')?>",
"type": "POST"
},
"columns": [
{ "data": "name", "orderable": false },
{ "data": "role" }
]
});