Datatable shows some warning when data is fetching from database using ajax - php

I am trying to listing data (between two dates) from database in to data tables via ajax. But data tables shows some warning message.
I am using laravel and jquery.
Data Tables warning: table id=callListDatatable - Requested unknown parameter '0' for row 0, column 0. For more information about this error, please see http://datatables.net/tn/4`
My console preview shows
[{
"call_from": "4915739463158",
"call_to": "4994156959988",
"direction": "in",
"answered_by": "voicemail_msg2",
"called_at": "2016-11-17 18:04:55",
"answered_at": null,
"hungup_at": null,
"duration_ring": "00:00:00",
"duration_call": "00:00:00"
}, {
"call_from": "49718280230",
"call_to": "4994156959988",
"direction": "in",
"answered_by": "voicemail_msg1",
"called_at": "2016-11-17 08:09:26",
"answered_at": null,
"hungup_at": null,
"duration_ring": "00:00:00",
"duration_call": "00:00:00"
}, {
"call_from": "491743078107",
"call_to": "4994156959982",
"direction": "in",
"answered_by": "Andreas Hauzenberger",
"called_at": "2016-11-17 09:16:14",
"answered_at": "2016-11-17 09:16:37",
"hungup_at": "2016-11-09 09:17:53",
"duration_ring": "00:00:23",
"duration_call": "00:01:16"
}]
I don't know what happen. Please help me to solve this issue.
Here is my jquery code
//Data table
$('#callListDatatable').DataTable({
"scrollX": true,
"lengthMenu": [[100, 250, 500, 1000, -1], [100, 250, 500, 1000, "All"]],
"order": [[ 4, "desc" ]],
"language": {
"sEmptyTable": "Keine Daten in der Tabelle vorhanden",
"sInfo": "_START_ bis _END_ von _TOTAL_ Einträgen",
"sInfoEmpty": "0 bis 0 von 0 Einträgen",
"sInfoFiltered": "(gefiltert von _MAX_ Einträgen)",
"sInfoPostFix": "",
"sInfoThousands": ".",
"sLengthMenu": "_MENU_ Einträge anzeigen",
"sLoadingRecords": "Wird geladen...",
"sProcessing": "Bitte warten...",
"sSearch": "Suchen",
"sZeroRecords": "Keine Einträge vorhanden.",
"oPaginate": {
"sFirst": "Erste",
"sPrevious": "Zurück",
"sNext": "Nächste",
"sLast": "Letzte"
},
"oAria": {
"sSortAscending": ": aktivieren, um Spalte aufsteigend zu sortieren",
"sSortDescending": ": aktivieren, um Spalte absteigend zu sortieren"
}
}
}).columns().every( function () {
var that = this;
$( 'input', this.footer() ).on( 'keyup change', function () {
if ( that.search() !== this.value ) {
that
.search( this.value )
.draw();
}
});
});
/*Data Tables functionality End*/
/* Date range functionality begin */
$('#reportrange').daterangepicker({
/*autoUpdateInput: false,*/
ranges: {
'Last 7 Days': [moment().subtract(7, 'days'), moment()],
'Last 30 Days': [moment().subtract(30, 'days'), moment()],
'This Month': [moment().startOf('month'), moment().endOf('month')],
'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
},
locale: {
format: 'DD.MM.YYYY'
}
});
$('#reportrange').on('apply.daterangepicker', function(ev, picker) {
$(this).val(picker.startDate.format('DD.MM.YYYY') + '-' + picker.endDate.format('DD.MM.YYYY'));
var data = $(".reportrange").val();
var daterange = data.replace(/\s/g, '');
/*$.getJSON('/call/list/daterange', {date: daterange }, function ( json ) {
$('#callListDatatable').dataTable().fnClearTable();
$('#callListDatatable').dataTable().fnAddData( json );
});*/
$.ajax({
type: "POST",
dataType: "json",
url: '/call/list/daterange',
data: {date: daterange },
success : function(data){
console.log(data);
$(data).each(function(key, value){
$('#callListDatatable').dataTable().fnClearTable();
$('#callListDatatable').dataTable().fnAddData( value )
});
}
});
});
Here is my controller code
public function show(Request $request)
{
/*dd($request->all());*/
$dateExplode = explode("-", $request->date);
$dateBegin = date('Y-m-d 00:00:00', strtotime($dateExplode[0]));
$dateEnd = date('Y-m-d 23:59:00', strtotime($dateExplode[1]));
$calls = Call::select('call_from', 'call_to', 'direction', 'answered_by', 'called_at', 'answered_at', 'hungup_at', 'duration_ring', 'duration_call')
->whereBetween('called_at', [$dateBegin, $dateEnd])
->get();
return json_encode($calls);
}

Problem with selector, use ID instead class.
var data = $(".reportrange").val();
change this to
var data = $("#reportrange").val();

Related

How to use data from database for chart.js (bubble chart) with Ajax/JSON method?

I would like to manipulate data from a database to use it with my bubble chart.
Here is what I did :
1) A data.php file that puts the requested data in JSON format:
​
<?php
/* data.php
* Description : Retourne le score Page Speed, le score Yslow et le libelle du site depuis la BDD.*/
​
//Header > JSON
header('Content-Type: application/json');
​
//Connexion Base de donnée
include ("../inc/connexion_bd.inc.php");
​
//Requête
$query = sprintf("SELECT
libelle_site,
score_pagespeed,
score_yslow
FROM
sites
INNER JOIN ANALYSE ON ANALYSE
.id_site = sites.id_site
INNER JOIN secteur_activite ON sites.id_secteur = secteur_activite.id_secteur
INNER JOIN(
SELECT sites.id_site,
MAX(date_analyse) AS last_analyse
FROM
sites
INNER JOIN ANALYSE ON ANALYSE
.id_site = sites.id_site
GROUP BY
sites.id_site
) AS TEMP
ON
TEMP.id_site = sites.id_site AND TEMP.last_analyse = ANALYSE.date_analyse
WHERE
secteur_activite.id_secteur = 5");
​
//Execution rapide de la requête
$result = $bdd->query($query);
​
//Boucle pour chaques résultats
$data = array();
foreach ($result as $row) {
$data[] = $row;
}
​
//Affichage du résultat
print json_encode($data);
> Result in the console :
https://zupimages.net/up/18/26/6jwb.png
2) A buble_db_php.js file that receives data from this page and creates the graph (Ajax) :
$(document).ready(function () {
​
/**
* Appel de la page data.php pour mettre les résultats de la BDD dans un tableau
*/
$.ajax({
url: "http://127.0.0.1/projets/Multi_Evaluation_Tool/api/data.php",
type: "GET",
success: function (data) {
console.log(data);
​
var site = {
//Libelle du site
label: [],
//Score 1
x: [],
//Score 2
y: []
};
​
var len = data.length;
​
for (var i = 0; i < len; i++) {
site.label.push(data[i].libelle_site); //On place le libelle du site dans la variable site.label
site.x.push(data[i].score_pagespeed); //On place le score PageSpeed du site dans la variable site.x
site.y.push(data[i].score_yslow); //On place le score Yslow du site dans la variable site.y
}
​
console.log(site);
​
//On récupère l'ID du graphique (canvas) situé dans la page result.php (bubble chart)
var ctx = $("#bubble-chart");
​
//Configuration des données et des options du graphique
var data = {
labels: ["Rapport entre les scores"],
datasets: [
{
label: site.label, //Libelle du site
backgroundColor: "rgba(255,221,50,0.2)",
borderColor: "rgba(255,221,50,1)",
data: [{
x: site.x, //Score 1
y: site.y, //Score 2
r: 10
}]
}
]
};
​
var options = {
title: {
display: true,
text: 'Rapport PageSpeed / Yslow'
},
scales: {
yAxes:
[{
scaleLabel: {
display: true,
labelString: "Score 1"
},
ticks: {
//Commencer à zéro ?
beginAtZero: true,
//Valeur maximum
max: 100
}
}],
xAxes:
[{
scaleLabel: {
display: true,
labelString: "Score 2"
},
ticks: {
//Commencer à zéro ?
beginAtZero: true,
//Valeur maximum
max: 100}
}]
}
};
var chart = new Chart(ctx, {
type: "bubble",
//On appel les données et les options configurées :
data: data,
options: options
});
},
error: function (data) {
console.log(data);
}
});
});
> Result in the console :
https://zupimages.net/up/18/26/845x.png
My problem ? All results are put in a single "bubble", as if we wanted a bar finally, except that it is bubulles. So I see my mistake but do not know how to correct it, I have to make another loop to ** create a bubble by result **? How to proceed ?
> My bubble chart, without bubles... :
https://zupimages.net/up/18/26/i936.png
Thank you in advance for your time going on reading all this and trying to help me.
PS : Sorry for my bad english...
Solved, thank you for your help !
https://examples.lartak.fr/graphs/bulles
jQuery(document).ready(function ($) {
var getSites = function () {
var ctx = $("#bubble-chart");
$.ajax({
url: 'http://127.0.0.1/projets/Multi_Evaluation_Tool/api/data.php',
type: 'GET',
dataType: 'JSON',
success: function (results) {
var dynamicColors = function () {
var r = Math.floor(Math.random() * 255);
var g = Math.floor(Math.random() * 255);
var b = Math.floor(Math.random() * 255);
return "rgb(" + r + "," + g + "," + b + ")";
};
var sites = [];
for (var i = 0; i < results.length; i++) {
var site = {
label: results[i].libelle_site.toString(),
backgroundColor: dynamicColors(),
borderColor: "rgb(69,70,72)",
radius: 10,
borderWidth: 1,
hoverBorderWidth: 2,
hoverRadius: 5,
data: [
{
x: Number(results[i].score_pagespeed),
y: Number(results[i].score_yslow),
r: 10
}
]
};
sites.push(site);
//console.log(sites);
}
console.log(sites);
var data = {labels: ["Rapport entre les scores"], datasets: sites};
var options = {
title: {display: true, text: 'Rapport score PageSpeed / Indice'},
scales: {
yAxes:
[
{
scaleLabel: {display: true, labelString: "Scores : Page Speed"},
ticks: {beginAtZero: true, max: 100}
}
],
xAxes:
[
{
scaleLabel: {display: true, labelString: "Indice"},
ticks: {beginAtZero: true, max: 100}
}
]
}
};
new Chart(ctx, {type: "bubble", data: data, options: options});
},
error: function (results) {
console.log(results);
}
});
};
getSites();
});

HighCharts, Json and Ajax

I have a php code that generates me a result in json format
<?php
header('Content-type: application/json');
include_once 'Conexion.php';
$objeto = new Conexion();
$conexion = $objeto->conectar();
$fecInicio = (isset($_POST['fechaInicio'])) ? $_POST['fechaInicio'] : '';
$fecFin = (isset($_POST['fechaFin'])) ? $_POST['fechaFin'] : '';
$consulta = "SELECT MONTHNAME(fecha), sum(totalVenta) FROM ventas WHERE fecha BETWEEN '$fecInicio' AND '$fecFin' GROUP BY MONTH(fecha)";
$resultado = $conexion->prepare($consulta);
$resultado->execute();
$result = array();
while ($fila = $resultado->fetch(PDO::FETCH_ASSOC)){
array_push($result, array($fila["MONTHNAME(fecha)"], $fila["sum(totalVenta)"])) ;
}
print json_encode($result);
$conexion=null;
With jquery ajax json I get and I want to use in data for a chart with Highcharts. This is the code of my JS
var chart1;
var options;
$(document).ready(function() {
var fechaInicio;
var fechaFin;
$("#generarReporte").click(function(){
fechaInicio = $("#fechaInicio").val();
fechaFin = $("#fechaFin").val();
$.ajax({
url: "../libreria/ORM/reportes.php",
type: "POST",
datatype:"json",
data: {fechaInicio:fechaInicio, fechaFin:fechaFin },
success: function(data) {
//recibo el json desde PHP y lo paso a string
var valores = JSON.stringify(data);
console.log(valores);
options.series[0].data = valores;
}
});
$("#opcion5").click();
});
$("#opcion5").click(function(){
var theModal = $("#modalGraficos").modal({
show: false
});
options = {
chart: {
renderTo: 'container1',
type: "column"
},
title: {
text: "Ventas Mensuales"
},
subtitle: {
text: "Período consultado, desde: <strong>"+fechaInicio+"</strong> hasta: <strong>"+fechaFin+"</strong>"
},
xAxis: {
type: "category",
labels: {
rotation: -45,
style: {
fontSize: "13px",
fontFamily: "Verdana, sans-serif"
}
}
},
yAxis: {
min: 0,
title: {
text: "Pesos AR$"
}
},
//establecemos los colores de las columnas por Mes
colors: [
"#4572A7",
"rgba(248, 44, 91, 0.61)",
"#89A54E",
"#80699B",
"#3D96AE",
"#DB843D",
"#92A8CD",
"#A47D7C",
"#B5CA92"
],
plotOptions: {
column: {
colorByPoint: true
}
},
legend: {
enabled: false
},
tooltip: {
pointFormat: "Total del Mes: <b>$ {point.y:.2f}</b>"
},
series: [{
name: "Ventas por mes",
dataLabels: {
enabled: true,
//rotation: -90,
rotation: 0,
color: "#ffffff",
align: "center",
format: "{point.y:,.2f}",
y: 30, // 10 pixels down from the top
style: {
fontSize: "13px",
fontFamily: "Verdana, sans-serif"
}
},
data:[
]
}]
}; //fin options
var chart1 = new Highcharts.Chart(options);
theModal.on("shown",function(){
// Recreate the chart now and it will be correct
});
theModal.modal("show");
});
});
The result console log is valid json format:
[["March","436400.00"],["April","1302261.50"]]
console log
I can not make the chart. It can help or assist? thank you very much
you need to set the data you get from ajax call to chart options. this link might help Load data into Highcharts with Ajax
A few clues:
Chart should mi inititailised in ajax callback
numbers shoudl not be a strings like you have. It should be [["March",436400.00],["April",1302261.50]]. To do that set the flag "JSON_NUMERIC_CHECK" in json_encode() function.

Hight Chart Dynamic Json Value is not loading in Series Data Section but Static Value is Loading Finely

Hi I have one issue i was creating one HighChart in this Static values to the series data section is working finely. but The same type value from a dynamic section is not showing.
function getusercategorygraph()
{
$.getJSON('config/alumniusermodes.php',function(data){
//alert(json);
//alert($.parseJSON(data));
//alert(obj);
var finaldata = '[';
var tmp = '';
var chart;
$.each(data, function( index, value ) {
finaldata += '{';
$.each(value, function( index, value ) {
//alert(index);
if(index === 'name')
{
tmp = " " + index + " : '" + value + "', ";
}
else
{
tmp = " " + index + " : " + value + ", ";
}
finaldata += tmp;
//alert("finaldata: " + finaldata);
});
finaldata+='},';
});
finaldata +=']';
//alert(finaldata);
chart = new Highcharts.Chart({
chart: {
/* backgroundColor: {
linearGradient: { x1: 0, y1: 0, x2: 1, y2: 1 },
stops: [
[0, 'rgb(0, 0, 0)'],
[1, 'rgb(0, 0, 0)']
]
},*/
renderTo : 'user-count',
type: 'column',
},
title: {
text: 'Alumni Users By Category Analytics'
},
xAxis: {
color:'#0077CC',
type: 'category'
},
yAxis: {
title: {
text: 'Total Number of Alumni Members'
}
},
legend: {
enabled: false
},
plotOptions: {
series: {
borderWidth: 0,
dataLabels: {
enabled: true,
format: '{point.y} Members'
}
}
},
tooltip: {
headerFormat: '<span style="font-size:11px">{series.name}</span><br>',
pointFormat: '<span style="color:{point.color}">{point.name}</span>: <b>{point.y} Members</b><br/>'
},
series: [{
name: "Alumni Type",
colorByPoint: true,
//sdata: [{ name : 'Standard', y : 52, },{ name : 'Silver', y : 24, },{ name : 'Gold', y : 20, },{ name : 'Platinum', y : 6, },]
data: [{ name : 'Standard', y : 52, },{ name : 'Silver', y : 24, },{ name : 'Gold', y : 20, },{ name : 'Platinum', y : 6, },]
//data : finaldata,
}],
});
///chart.series[2].data.push(finaldata);
});
}
i am getting final data like this only
[{ name : 'Standard', y : 52, },{ name : 'Silver', y : 24, },{ name : 'Gold', y : 20, },{ name : 'Platinum', y : 6, },]
but i cant load that in this graph but when paste same value in static mode its showing correctly.
now its showinng a blank section only.
I am new to HighCharts Please help. Thanks in advance.
Your code is creating finaldata as a string, when you want to produce an array. You should have better luck with something like this:
// Create a new array
var finaldata = []
var chart;
// Perform your operations
$.each(data, function( index, value ) {
// Create a new hash
var currentItem = {}
// Create the proper values in your hash
$.each(value, function( index, value ) {
currentItem[index] = value;
});
// Push the new hash to the array
finaldata += currentItem;
});
If all of your data is being passed in a way that your old code successfully created the string you shared, then this should build the object for which you are looking.
To test this you may first want to try leaving your code exactly how it is, and parsing the string to JSON:
// Use this instead of 'data : finaldata'
data: JSON.parse( finaldata ),
This will try to turn your string into the objects on which you are trying to operate. That said, it would be in poor form to practice building an array via string manipulation. I would very strongly encourage you to follow the first approach I detailed.
Hi i Found this as For My Query.
var finaldata = [];
$.getJSON('config/alumniusermodes.php',function(data){
// Create a new array
var finaldata = [];
var chart;
var categories = [];
var tools = [];
$.each(data, function( index, value ) {
var currentItem = {}
finaldata.push({
name: value.name,
y: parseFloat(value.y)
});
});
var chart = new Highcharts.Chart({
chart: {
renderTo : 'user-count',
type: 'column',
},
title: {
text: 'Alumni Users By Category Analytics'
},
xAxis: {
color:'#0077CC',
categories: categories
},
yAxis: {
title: {
text: 'Total Number of Alumni Members'
}
},
legend: {
enabled: false
},
plotOptions: {
series: {
borderWidth: 0,
dataLabels: {
enabled: true,
format: '{point.y} Members'
}
}
},
tooltip: {
headerFormat: '<span style="font-size:11px">{series.name}</span><br>',
pointFormat: '<span style="color:{point.color}">{point.name}</span>: <b>{point.y} Members</b><br/>'
},
series: [{
name: "Alumni Type",
colorByPoint: true,
data : finaldata,
}],
});
});
This is my right coding which solved my issue

Flot Charts using SQL Server db with multiple y axis

This is my first post, apologies if I've asked a question a number of people have already done so. I don't see the answer I need in other posts.
I'm using Flot Charts and have a SQL Server db, I've got a php file that will connect to the db and return all the values within the sql in an array.
<?php
$server = "XXXX";
$database = "XXXX";
$user = "ReportsUser";
$pwd = "ReportsUser";
$cnn = odbc_connect("Driver={SQL Server Native Client 10.0};Server=$server;Database=$database;", $user, $pwd);
if(!$cnn)
{
echo "error in connecting";
}
$sql = odbc_exec($cnn, "
SELECT Months
,Referrals
,ProjectedVol
FROM mis.ReferralsBudgetvsActual
WHERE Months <= MONTH(GETDATE())
");
while($result = odbc_fetch_array($sql))
{
$allreferrals[] = array($result['Months'],$result['Referrals'],$result['ProjectedVol']);
}
echo json_encode(($allreferrals), JSON_NUMERIC_CHECK);
exit;
?>
This works well and produces the array as below
[[1,5981,7465],[2,5473,6962],[3,4974,7391],[4,5731,6985],[5,5891,7080],[6,5168,7136],[7,5551,7543],[8,4427,7242],[9,4617,7204],[10,4807,7642]]
Now, when it all comes together in the jquery file, this is where I end up getting stuck. I don't see where it pulls any other columns back apart from the first data column, how can this be done?
// document ready function
$(document).ready(function() {
var chartColours = ['#88bbc8', '#ed7a53', '#9FC569', '#bbdce3', '#9a3b1b', '#5a8022', '#2c7282'];
// function for refreshing shiftstats chart
make_chart();
function make_chart() {
$.ajax({
cache: 'false',
type: 'GET',
dataType: 'json',
url: "test.php",
success: function(data) {
var d1 = data;
var d2 = data;
//define placeholder class
var placeholder = $(".shifts-chart");
//graph options
var options = {
grid: {
show: true,
aboveData: true,
color: "#3f3f3f" ,
labelMargin: 5,
axisMargin: 0,
borderWidth: 0,
borderColor:null,
minBorderMargin: 5 ,
clickable: true,
hoverable: true,
autoHighlight: true,
mouseActiveRadius: 20
},
series: {
grow: {
active: false,
stepMode: "linear",
steps: 50,
stepDelay: true
},
lines: {
show: true,
fill: false,
lineWidth: 4,
steps: false
},
points: {
show:true,
radius: 5,
symbol: "circle",
fill: true,
borderColor: "#fff"
}
},
legend: {
position: "ne",
margin: [0,-25],
noColumns: 0,
labelBoxBorderColor: null,
labelFormatter: function(label, series) {
// just add some space to labes
return label+' ';
}
},
yaxis: { min: 0 },
xaxis: {ticks:11, tickDecimals: 0},
colors: chartColours,
shadowSize:1,
tooltip: true, //activate tooltip
tooltipOpts: {
content: "%s : %y.0",
shifts: {
x: -30,
y: -50
}
}
};
$.plot(placeholder,
[{
label: "Referrals",
data: d1,
lines: {fillColor: "#f2f7f9"},
points: {fillColor: "#88bbc8"}
},
{
label: "ProjectedVol",
data: d2,
lines: {fillColor: "#f2f7f9"},
points: {fillColor: "#88bbc8"}
}
], options);
}
});
}
});
Thanks
You'll need to change your php array creation to properly format the data into two series:
$d1 = array();
$d2 = array();
while($result = odbc_fetch_array($sql))
{
array_push($d1, array($result['Months'], $result['Referrals']));
array_push($d2, array($result['Months'], $result['ProjectedVol']));
}
$allreferrals = array($d1, $d2);
echo json_encode(($allreferrals), JSON_NUMERIC_CHECK);
This should return it as an array of arrays:
[
[[1,5981],[2,5473],[3,4974],[4,5731],[5,5891],[6,5168],[7,5551],[8,4427],[9,4617,7204],[10,4807]],
[[1,7465],[2,6962],[3,7391],[4,6985],[5,7080],[6,7136],[7,7543],[8,7242],[9,7204],[10,7642]]
]
(Hopefully I have the syntax correct, I'm not a fan of php)
Update from comment
If you are returning a slew of series, you might be better returning an associative array from PHP:
$allreferrals = array('ref' => array(), 'projVol'=> array());
while($result = odbc_fetch_array($sql))
{
array_push($allreferrals['ref'], array($result['Months'], $result['Referrals']));
array_push($allreferrals['projVol'], array($result['Months'], $result['ProjectedVol']));
}
echo json_encode(($allreferrals), JSON_NUMERIC_CHECK);
Then back in the javascript:
$.plot(placeholder,
[{
label: "Referrals",
data: data["ref"]
},
{
label: "ProjectedVol",
data: data["projVol"]
}],
options);

Search multiple datepicker on same grid

I'm using multiple datepicker on same grid and I face the problem to get a proper result.
I used 3 datepicker in 1 grid.
Only the first datepicker (Order Date)is able to output proper result while the other 2 datepicker (Start Date & End Date) are not able to generate proper result.
There is no problem with the query, so could you find out what's going on here?
Thanks in advance!
php wrapper
<?php
ob_start();
require_once 'config.php';
// include the jqGrid Class
require_once "php/jqGrid.php";
// include the PDO driver class
require_once "php/jqGridPdo.php";
// include the datepicker
require_once "php/jqCalendar.php";
// Connection to the server
$conn = new PDO(DB_DSN,DB_USER,DB_PASSWORD);
// Tell the db that we use utf-8
$conn->query("SET NAMES utf8");
// Create the jqGrid instance
$grid = new jqGridRender($conn);
// Write the SQL Query
$grid->SelectCommand = "SELECT c.CompanyID, c.CompanyCode, c.CompanyName, c.Area, o.OrderCode, o.Date, m.maID ,m.System, m.Status, m.StartDate, m.EndDate, m.Type FROM company c, orders o, maintenance_agreement m WHERE c.CompanyID = o.CompanyID AND o.OrderID = m.OrderID ";
// Set the table to where you update the data
$grid->table = 'maintenance_agreement';
// set the ouput format to json
$grid->dataType = 'json';
// Let the grid create the model
$grid->setPrimaryKeyId('maID');
// Let the grid create the model
$grid->setColModel();
// Set the url from where we obtain the data
$grid->setUrl('grouping_ma_details.php');
// Set grid caption using the option caption
$grid->setGridOptions(array(
"sortable"=>true,
"rownumbers"=>true,
"caption"=>"Group by Maintenance Agreement",
"rowNum"=>20,
"height"=>'auto',
"width"=>1300,
"sortname"=>"maID",
"hoverrows"=>true,
"rowList"=>array(10,20,50),
"footerrow"=>false,
"userDataOnFooter"=>false,
"grouping"=>true,
"groupingView"=>array(
"groupField" => array('CompanyName'),
"groupColumnShow" => array(true), //show or hide area column
"groupText" =>array('<b> Company Name: {0}</b>',),
"groupDataSorted" => true,
"groupSummary" => array(true)
)
));
//Start Date
$grid->setColProperty("StartDate", array("label"=>"Start Date","width"=>120,"align"=>"center","fixed"=>true,
"formatter"=>"date",
"formatoptions"=>array("srcformat"=>"Y-m-d H:i:s","newformat"=>"d M Y")
));
$grid->setUserTime("d M Y");
$grid->setUserDate("d M Y");
$grid->setDatepicker("StartDate",array("buttonOnly"=>false));
$grid->datearray = array('StartDate');
//End Date
$grid->setColProperty("EndDate", array("label"=>"End Date","width"=>120,"align"=>"center","fixed"=>true,
"formatter"=>"date",
"formatoptions"=>array("srcformat"=>"Y-m-d H:i:s","newformat"=>"d M Y")
));
$grid->setUserTime("d M Y");
$grid->setUserDate("d M Y");
$grid->setDatepicker("EndDate",array("buttonOnly"=>false));
$grid->datearray = array('EndDate');
//Order Date
$grid->setColProperty("Date", array("label"=>"Order Date","width"=>100,"editable"=>false,"align"=>"center","fixed"=>true,
"formatter"=>"date",
"formatoptions"=>array("srcformat"=>"Y-m-d H:i:s","newformat"=>"d M Y")
));
$grid->setUserTime("d M Y");
$grid->setUserDate("d M Y");
$grid->setDatepicker("Date",array("buttonOnly"=>false));
$grid->datearray = array('Date');
// Enable toolbar searching
$grid->toolbarfilter = true;
$grid->setFilterOptions(array("stringResult"=>true,"searchOnEnter"=>false,"defaultSearch"=>"cn"));
// Enable navigator
$grid->navigator = true;
$grid->setNavOptions('navigator', array("pdf"=>true, "excel"=>true,"add"=>false,"edit"=>true,"del"=>false,"view"=>true, "search"=>true));
$grid->renderGrid('#grid','#pager',true, null, null, true,true);
$conn = null;
?>
javascript code
jQuery(document).ready(function ($) {
jQuery('#grid').jqGrid({
"width": 1300,
"hoverrows": true,
"viewrecords": true,
"jsonReader": {
"repeatitems": false,
"subgrid": {
"repeatitems": false
}
},
"xmlReader": {
"repeatitems": false,
"subgrid": {
"repeatitems": false
}
},
"gridview": true,
"url": "grouping_ma_details.php",
"editurl": "grouping_ma_details.php",
"cellurl": "grouping_ma_details.php",
"sortable": true,
"rownumbers": true,
"caption": "Group by Maintenance Agreement",
"rowNum": 20,
"height": "auto",
"sortname": "maID",
"rowList": [10, 20, 50],
"footerrow": false,
"userDataOnFooter": false,
"grouping": true,
"groupingView": {
"groupField": ["CompanyName"],
"groupColumnShow": [true],
"groupText": ["<b> Company Name: {0}</b>"],
"groupDataSorted": true,
"groupSummary": [true]
},
"datatype": "json",
"colModel": [{
"name": "CompanyID",
"index": "CompanyID",
"sorttype": "int",
"editable": true
}, {
"name": "CompanyCode",
"index": "CompanyCode",
"sorttype": "string",
"editable": true
}, {
"name": "CompanyName",
"index": "CompanyName",
"sorttype": "string",
"editable": true
}, {
"name": "Area",
"index": "Area",
"sorttype": "string",
"editable": true
}, {
"name": "OrderCode",
"index": "OrderCode",
"sorttype": "string",
"editable": true
}, {
"name": "Date",
"index": "Date",
"sorttype": "date",
"label": "Order Date",
"width": 100,
"editable": false,
"align": "center",
"fixed": true,
"formatter": "date",
"formatoptions": {
"srcformat": "Y-m-d H:i:s",
"newformat": "d M Y"
},
"editoptions": {
"dataInit": function (el) {
setTimeout(function () {
if (jQuery.ui) {
if (jQuery.ui.datepicker) {
jQuery(el).datepicker({
"disabled": false,
"dateFormat": "dd M yy"
});
jQuery('.ui-datepicker').css({
'font-size': '75%'
});
}
}
}, 100);
}
},
"searchoptions": {
"dataInit": function (el) {
setTimeout(function () {
if (jQuery.ui) {
if (jQuery.ui.datepicker) {
jQuery(el).datepicker({
"disabled": false,
"dateFormat": "dd M yy"
});
jQuery('.ui-datepicker').css({
'font-size': '75%'
});
}
}
}, 100);
}
}
}, {
"name": "maID",
"index": "maID",
"sorttype": "int",
"key": true,
"editable": true
}, {
"name": "System",
"index": "System",
"sorttype": "string",
"editable": true
}, {
"name": "Status",
"index": "Status",
"sorttype": "string",
"editable": true
}, {
"name": "StartDate",
"index": "StartDate",
"sorttype": "date",
"label": "Start Date",
"width": 120,
"align": "center",
"fixed": true,
"formatter": "date",
"formatoptions": {
"srcformat": "Y-m-d H:i:s",
"newformat": "d M Y"
},
"editoptions": {
"dataInit": function (el) {
setTimeout(function () {
if (jQuery.ui) {
if (jQuery.ui.datepicker) {
jQuery(el).datepicker({
"disabled": false,
"dateFormat": "dd M yy"
});
jQuery('.ui-datepicker').css({
'font-size': '75%'
});
}
}
}, 100);
}
},
"searchoptions": {
"dataInit": function (el) {
setTimeout(function () {
if (jQuery.ui) {
if (jQuery.ui.datepicker) {
jQuery(el).datepicker({
"disabled": false,
"dateFormat": "dd M yy"
});
jQuery('.ui-datepicker').css({
'font-size': '75%'
});
}
}
}, 100);
}
},
"editable": true
}, {
"name": "EndDate",
"index": "EndDate",
"sorttype": "date",
"label": "End Date",
"width": 120,
"align": "center",
"fixed": true,
"formatter": "date",
"formatoptions": {
"srcformat": "Y-m-d H:i:s",
"newformat": "d M Y"
},
"editoptions": {
"dataInit": function (el) {
setTimeout(function () {
if (jQuery.ui) {
if (jQuery.ui.datepicker) {
jQuery(el).datepicker({
"disabled": false,
"dateFormat": "dd M yy"
});
jQuery('.ui-datepicker').css({
'font-size': '75%'
});
}
}
}, 100);
}
},
"searchoptions": {
"dataInit": function (el) {
setTimeout(function () {
if (jQuery.ui) {
if (jQuery.ui.datepicker) {
jQuery(el).datepicker({
"disabled": false,
"dateFormat": "dd M yy"
});
jQuery('.ui-datepicker').css({
'font-size': '75%'
});
}
}
}, 100);
}
},
"editable": true
}, {
"name": "Type",
"index": "Type",
"sorttype": "string",
"editable": true
}],
"postData": {
"oper": "grid"
},
"prmNames": {
"page": "page",
"rows": "rows",
"sort": "sidx",
"order": "sord",
"search": "_search",
"nd": "nd",
"id": "maID",
"filter": "filters",
"searchField": "searchField",
"searchOper": "searchOper",
"searchString": "searchString",
"oper": "oper",
"query": "grid",
"addoper": "add",
"editoper": "edit",
"deloper": "del",
"excel": "excel",
"subgrid": "subgrid",
"totalrows": "totalrows",
"autocomplete": "autocmpl"
},
"loadError": function (xhr, status, err) {
try {
jQuery.jgrid.info_dialog(jQuery.jgrid.errors.errcap, '<div class="ui-state-error">' + xhr.responseText + '</div>', jQuery.jgrid.edit.bClose, {
buttonalign: 'right'
});
} catch (e) {
alert(xhr.responseText);
}
},
"pager": "#pager"
});
jQuery('#grid').jqGrid('navGrid', '#pager', {
"edit": true,
"add": false,
"del": false,
"search": true,
"refresh": true,
"view": true,
"excel": true,
"pdf": true,
"csv": false,
"columns": false
}, {
"drag": true,
"resize": true,
"closeOnEscape": true,
"dataheight": 150,
"errorTextFormat": function (r) {
return r.responseText;
}
}, {
"drag": true,
"resize": true,
"closeOnEscape": true,
"dataheight": 150,
"errorTextFormat": function (r) {
return r.responseText;
}
}, {
"errorTextFormat": function (r) {
return r.responseText;
}
}, {
"drag": true,
"closeAfterSearch": true,
"multipleSearch": true
}, {
"drag": true,
"resize": true,
"closeOnEscape": true,
"dataheight": 150
});
jQuery('#grid').jqGrid('navButtonAdd', '#pager', {
id: 'pager_excel',
caption: '',
title: 'Export To Excel',
onClickButton: function (e) {
try {
jQuery("#grid").jqGrid('excelExport', {
tag: 'excel',
url: 'grouping_ma_details.php'
});
} catch (e) {
window.location = 'grouping_ma_details.php?oper=excel';
}
},
buttonicon: 'ui-icon-newwin'
});
jQuery('#grid').jqGrid('navButtonAdd', '#pager', {
id: 'pager_pdf',
caption: '',
title: 'Export To Pdf',
onClickButton: function (e) {
try {
jQuery("#grid").jqGrid('excelExport', {
tag: 'pdf',
url: 'grouping_ma_details.php'
});
} catch (e) {
window.location = 'grouping_ma_details.php?oper=pdf';
}
},
buttonicon: 'ui-icon-print'
});
jQuery('#grid').jqGrid('filterToolbar', {
"stringResult": true,
"searchOnEnter": false,
"defaultSearch": "cn"
});
});
If one uses searching toolbar (filterToolbar) it can be specified only one operation used during searching. You used
$('#grid').jqGrid('filterToolbar',
{ stringResult: true, searchOnEnter: false, defaultSearch: "cn" });
So the operation "Contains" ("cn") will be apply on all columns during filtering where sopt of searchoptions is not specified. It's extremely important to include sopt of searchoptions for all columns having stype: "select".
If you don't use Searching Dialog then you can include sopt: ["eq"] in searchoptions for all columns having stype: "select" and formatter: "date". If you use Searching Dialog additionally to Searching Toolbar you should in sopt with some array where "eq" is the first element of the array. In the case the operation "Equal" will be used during filtering of the grid.
Because you use Advanced Searching Dialog (with multipleSearch: true) you can verify the filter generated by the Searching Toolbar very easy. You need just set any filter (or filters) and then open Searching Dialog after that. If you don't opened the searching dialog before you will see the filter generated by searching filter. I recommend you to use recreateForm: true option together with multipleSearch: true (or probably with multipleGroup: true). In the case you will always see the current used filter in the searching dialog instead of the last searching dialog (it will be hide instead of destroying).

Categories