Not able to export jqgrid table as excel/pdf. - php

I successfully created a small jqgrid table. I'm trying to export this table to an excel or pdf file using Jquery. I am new to jquery and jqgrid. Could someone please let me know what is wrong in the code? I would really appreciate some help or suggestions.
I found the export function online. It said I have to just call this function with the grid id. Am I doing something wrong?
export.php file:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<link href="CSS/CalibrationKit.css" rel="stylesheet" type="text/css">
<!-- ------------------------JQGRID files-------------------------------- -->
<link rel="stylesheet" type="text/css" media="screen" href="jquery/css/jquery-ui-1.7.1.custom.css" />
<link rel="stylesheet" type="text/css" media="screen" href="css/ui.jqgrid.css" />
<script src="jquery/js/jquery-1.11.0.min.js" type="text/javascript"></script>
<script src="jquery/js/i18n/grid.locale-en.js" type="text/javascript"></script>
<script src="jquery/js/jquery.jqGrid.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(e) {
/*jqgrid*/
var mydata = [{
head_mean_volume: "50",
head_std_dev: "2",
head_cv: "3",
offset_factor: "4",
scaling_factor: "5"
}];
$("#projectSpreadsheet").jqGrid({
data: mydata,
datatype: "local",
colNames: ["Head Mean Volume Dispensed", "Head Standard Deviation", "Head %CV", "Whole Head Offset Factor", "Whole Head Scaling Factor"],
colModel: [{
name: 'head_mean_volume',
index: 'head_mean_volume',
editable: false,
}, {
name: 'head_std_dev',
index: 'head_std_dev',
editable: false,
}, {
name: 'head_cv',
index: 'head_cv',
editable: false,
}, {
name: 'offset_factor',
index: 'offset_factor',
editable: false,
}, {
name: 'scaling_factor',
index: 'scaling_factor',
editable: false,
}],
'cellEdit': false,
'cellsubmit' : 'clientArray',
editurl: 'clientArray'
}); /*jqGrid close */
/* createExcelFromGrid */
$('#btnSun').click(function() {
$.fn.myFunction("projectSpreadsheet");
});
$.fn.myFunction = function(gridID,filename) {
var grid = $('#' + gridID);
var rowIDList = grid.getDataIDs();
var row = grid.getRowData(rowIDList[0]);
var colNames = [];
var i = 0;
for(var cName in row) {
colNames[i++] = cName; // Capture Column Names
}
var html = "";
for(var j=0;j<rowIDList.length;j++) {
row = grid.getRowData(rowIDList[j]); // Get Each Row
for(var i = 0 ; i<colNames.length ; i++ ) {
html += row[colNames[i]] + ';'; // Create a CSV delimited with ;
}
html += '\n';
}
html += '\n';
var a = document.createElement('a');
a.id = 'ExcelDL';
a.href = 'data:application/vnd.ms-excel,' + html;
a.download = filename ? filename + ".xls" : 'DataList.xls';
document.body.appendChild(a);
a.click(); // Downloads the excel document
document.getElementById('ExcelDL').remove();
}
}); /* function close */
</script>
</head>
<body>
<table id="projectSpreadsheet" class="fixed_headers" style="width:875px"></table>
<br><br>
<button id="btnSun">Export Table data into Excel</button>
</body>
</html>

Replace your function with this one and let me know if it works for you.
function(gridID,filename) {
var html = $('#gview_' + gridID).html();
var a = document.createElement('a');
a.id = 'tempLink';
a.href = 'data:application/vnd.ms-excel,' + html;
a.download = filename + ".xls";
document.body.appendChild(a);
a.click(); // Downloads the excel document
document.getElementById('tempLink').remove();
}

Related

How to filter a JSON page feeding data to Select2?

I'm trying to populate a Select2 box with data from a t-sql query. The query is run on a PHP page which translates the output to JSON and is called in the javascript of the main page.
The main page looks like this:
<?php
header('Content-type: text/html; charset=UTF-8');
require('db.php'); // Bring in the database connection
include("auth.php"); // Make sure the user is logged in to an account
?>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" http-equiv="Content Type" charset="utf-8"/>
<!-- JQuery -->
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- SELECT 2 -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>
</head>
<body style="background-color: #F5F5F5;">
<select class="js-data-example-ajax">
</select>
<script>
$('.js-data-example-ajax').select2({
width: '250px',
ajax: {
url: 'http://10.1.248.41/TFM-Project/ImportINjson.php',
dataType: 'json'
// Additional AJAX parameters go here
}
});
</script>
</body>
</html>
My JSON page looks like this:
<?php
require('db.php'); // Bring in the database connection
include("auth.php"); // Make sure the user is logged in to an account
$search = $_GET['search'];
//JSON Table Stuff
$sql = "SELECT DISTINCT [IN] AS id, Nom as text
FROM dbo.[TFM_NumérosIN2012]
;";
$stmt = sqlsrv_query($con,$sql);
$result = array();
do {
while($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
$result[] = $row;
}
} while (sqlsrv_next_result($stmt));
sqlsrv_free_stmt($stmt);
$data2 = json_encode($result);
echo '{ "results":' . $data2 . '}';
?>
The data output by the JSON page looks like this:
{ "results":[{"id":2,"text":"SMITH Sean"},{"id":3,"text":"CHARLES charley"},{"id":4,"text":"TFC Madrid"},{"id":5,"text":"VAN DAMME jean claude"}]}
The data is loading into the select list without any problems. However, I've tried to filter the data multiple ways and nothing has worked. I've tried adding a data parameter and passing a search variable to the php/JSON page and referencing in the $sql variable as a where clause, but this doesn't return anything
To try and filter the data I changed the javascript to this:
$('.js-data-example-ajax').select2({
width: '250px',
ajax: {
url: 'http://10.1.248.41/TFM-Project/ImportINjson.php',
dataType: 'json',
data: function (params) {
var query = {
search: params.term
}
// Query parameters will be ?search=[term]&type=public
return query;
}
}
});
But this breaks my select and and it displays a message 'The results could not be loaded.'
Does anyone know what I'm doing wrong here?
Cheers,
At the end of your php file just echo the following line :
echo json_encode($result);
In your html/js file :
<link href='https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css' rel='stylesheet' type='text/css'>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js'></script>
<select name='js-data-example-ajax' class='js-data-example-ajax'></select>
$(document).ready(function()
{
$('.js-data-example-ajax').select2({
placeholder: "Search for product",
minimumInputLength: 1,
width: '250px',
ajax: {
url: 'http://10.1.248.41/TFM-Project/ImportINjson.php',
dataType: 'json',
data: function (params) {
var query = {
search: params.term,
type: 'public'
}
console.log("query : "+query.search);
return query;
},
processResults: function (response) {
console.log("response : "+response);
return {
results: $.map(response, function(obj) {
console.log("response obj.id: "+obj.id);
console.log("response obj.text: "+obj.text);
return { id: obj.id, text: obj.text };
})
};
},
cache: false
}
});
});

JSON, PHP & SQL implementation error

I'm trying to work out how to use JSON, php and SQL (initially MSSQL) to populate a type-ahead field of names and, once the name is selected, to also populate a job title and department. This is my first time to use JSON, so I'm starting a bit from scratch here.
I got a partial solution from Experts Exchange (see Fiddle) using static data, but I'm having trouble converting the data I'm pulling from the database to what is being shown in the fiddle.
The code for the fiddle is:-
<!DOCTYPE html>
<html>
<head>
<title>Autocomplete Textbox Demo | PHP | jQuery</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<script type="text/javascript">
$(function() {
var availableTags = [{
empName: "A1",
empTitle: "AAA1 AAAAA"
}, {
empName: "A2",
empTitle: "AAA2 AAAAA"
}, {
empName: "B",
empTitle: "AAA AAAAA"
}, {
empName: "C",
empTitle: "AAA AAAAA"
}];
var empNames = [];
var empTitles = [];
$(availableTags).each(function(ix, v) {
empNames.push(v.empName);
empTitles.push(v.empTitle);
});
$("#empName").autocomplete({
source: empNames,
autoFocus: true,
select: function(event, ui) {
//console.log(event);
//console.log(ui);
//console.log(getTitle(ui.item.label));
$("#empTitle").val(getTitle(ui.item.label));
}
});
$("#empTitle").autocomplete({
source: empTitles,
autoFocus: true,
select: function(event, ui) {
//console.log(event);
//console.log(ui);
//console.log(getName(ui.item.label));
$("#empName").val(getName(ui.item.label));
}
});
function getName(t) {
//console.log("title:" + t);
for (k in availableTags)
if (availableTags[k].empTitle == t) return availableTags[k].empName;
};
function getTitle(n) {
//console.log("name:" + n);
for (k in availableTags) {
//console.log("k:" + availableTags[k].empName + " > " + availableTags[k].empTitle);
if (availableTags[k].empName == n) return availableTags[k].empTitle;
}
};
});
</script>
</head>
<body>
<label>Department Name</label></br>
<input id="empName" type="text" size="50" /><br>
<input id="empTitle" type="text" size="50" />
</body>
</html>
I'm stuck now on implementing the results returned from the database query to work with the fiddle. I believe I've to the data correctly formatted but it's wrong somewhere and I'm not sure where that is.
I'm getting the data from an SQL table with a separate php page called fetchEmpName.php:-
<?php
require('i_PDOConnection.php');
$query = "SELECT empFName + ' ' + empLName as [empName], empTitle, empDept FROM tbl_CouncilStaff WHERE active = 1 AND display = 1 AND (empFName LIKE '%".$search."%' OR empLName LIKE '%".$search."%') ORDER BY empLName";
$stmt = $dbh->prepare($query);
$stmt->execute();
$data = $stmt->fetchAll();
$return_arr = array();
$return_arr['contacts'] = array();
foreach ($data as $row) {
$dataArray['empName'] = $row['empName'];
$dataArray['empTitle'] = $row['empTitle'];
array_push($return_arr['contacts'],$dataArray);
}
echo json_encode($return_arr);
?>
Which (according to the Chrome console log, produces an array like:
{empName: "Bob Smith", empTitle: "Chief Cook and Bottle Washer"}
Which works properly when I replace the fiddle data with the generated data but fails once the static data is replaced by the sql code. So that tells me that the problem lies in the script. At this point, the page has morphed into:
<!DOCTYPE html>
<html>
<head>
<title>Autocomplete Textbox Demo | PHP | jQuery</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<script type="text/javascript">
$(function() {
var availableTags = <?php include('fetchEmpName2.php'); ?>;
var empNames = [];
var empTitles = [];
$(availableTags).each(function(x, y) {
empNames.push(y.empName);
empTitles.push(y.empTitle);
});
$("#empName").autocomplete({
source: empNames,
autoFocus: true,
select: function(event, ui) {
// console.log(event);
// console.log(ui);
// console.log(getTitle(ui.item.label));
$("#empTitle").val(getTitle(ui.item.label));
}
});
$("#empTitle").autocomplete({
source: empTitles,
autoFocus: true,
select: function(event, ui) {
//console.log(event);
//console.log(ui);
//console.log(getName(ui.item.label));
$("#empName").val(getName(ui.item.label));
}
});
function getName(t) {
//console.log("title:" + t);
for (k in availableTags)
if (availableTags[k].empTitle == t) return availableTags[k].empName;
};
function getTitle(n) {
//console.log("name:" + n);
for (k in availableTags) {
//console.log("k:" + availableTags[k].empName + " > " + availableTags[k].empTitle);
if (availableTags[k].empName == n) return availableTags[k].empTitle;
}
};
console.log(availableTags);
});
</script>
</head>
<body>
<label>Department Name</label></br>
<input id="empName" type="text" size="50" /><br>
<input id="empTitle" type="text" size="50" />
</body>
</html>
When I run the page, the jquery library throws an error saying
jquery-ui.min.js:8 Uncaught TypeError: Cannot read property 'label' of undefined"
I hope this is enough for someone to sort out where I'm off track - or if there is a better way to solving the problem of filling additional fields from a type-ahead field.
Thanks in advance - any assistance offered would be greatly appreciated.

Refresh getJSON in PHP with new data from datepicker

I have two files, index.php, and showday.php.
index.php is supposed to display a graph with help of canvasjs
The data for canvasjs comes from showday.php, which runs MySQL queries to extract data
The files shown here do show a proper graph when Year, Month, and Day variables have hard coded values in showday.php, therefore I know that the concept works.
My questions are:
- How to load index.php with current date sent to showday.php, and
- How to refresh $.getJSON with new date selected by the datepicker
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="jqueryui/themes/sunny/jquery-ui.css">
<link rel="stylesheet" href="jqueryui/style.css">
<script src="jquery/jquery-3.1.0.js"></script>
<script src="jqueryui/jquery-ui.js"></script>
<script src="canvas/jquery.canvasjs.min.js"></script>
<script>
$( function() {
$( "#datepicker" ).datepicker({
changeMonth: true,
changeYear: true
});
} );
I guess that changedate function goes here with new date.
But how to put that date in the call to:
$.getJSON("showday.php", function (result) ???
Also, I would like that the page loads with current date,
and then a user can refresh the graph with a chosen date
with help of datepicker. How to do that?
$(document).ready(function ()
{
$.getJSON("showday.php", function (result)
{
var chart = new CanvasJS.Chart("chartContainer",
{
zoomEnabled: true,
axisY:{
title: "Power",
includeZero: false,
suffix : " kW",
},
axisX: {
title: "Time",
},
data: [
{
type: "spline",
lineColor: "#FFAA00",
lineThickness: 2,
markerColor: "#007700",
dataPoints: result
}
]
}
);
chart.render();
}
);
}
);
</script>
</head>
<body>
<div id="chartContainer" style="width: 800px; height: 400px;"></div>
<form action="">
Date: <input type="text" id="datepicker" onchange="changedate(this.value)">
</form>
</body>
</html>
showday.php
<?php
$con = mysqli_connect('localhost', 'db', 'password', 'table');
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to DataBase: " . mysqli_connect_error();
}else
{
$data_points = array();
**How the new date vlues coming from index.php can be plugged in here?**
$query = "SELECT Hour, Minute, PAC as kW FROM `logdata` WHERE (Year=?) AND (Month=?) AND (Day=?)";
$result = mysqli_query($con, $query);
while($row = mysqli_fetch_array($result))
{
$Time = $row['Hour'].":".$row['Minute'];
$point = array("label" => $Time , "y" => $row['kW']);
array_push($data_points, $point);
}
echo json_encode($data_points, JSON_NUMERIC_CHECK);
}
mysqli_close($con);
?>
Create a function:
function updateChart() {
$.getJSON("showday.php", {date: $('#datepicker').datepicker('getDate')}, function (result)
{
var chart = new CanvasJS.Chart("chartContainer",
{
zoomEnabled: true,
axisY:{
title: "Power",
includeZero: false,
suffix : " kW",
},
axisX: {
title: "Time",
},
data: [
{
type: "spline",
lineColor: "#FFAA00",
lineThickness: 2,
markerColor: "#007700",
dataPoints: result
}
]
}
);
chart.render();
}
);
}
Call updateChart() on datepicker select, and $(document).ready(). Pass data through $.getJSON by passing an object as the second parameter.
Access the date with php (In your showday.php) by using $_GET['date']. See this post on how to extract the year/date/month from the string provided.

Highcharts doesn't update from file

I use Highcharts and when I update the site it doesn't update the data from which it constructs the graph.
I take the data from mysql, save it in a .csv file and open the .csv in highcharts. It seems to save the old values in the graph even if the .csv file is updated.
<?php
unlink('column-data.csv'); //This file must exist or else it gives error
include 'database.php';
$result = mysql_query("SELECT
value
FROM
data
INTO OUTFILE 'C:/xampp/htdocs/arduinoproj/test3/column-data.csv'
FIELDS ENCLOSED BY '\,'
TERMINATED BY ';'
ESCAPED BY '\"'
")
or die("Could not issue MySQL query");
include 'highcharts.php'
?>
..and the highcharts code is more or less unchanged.
The changed code from the original is in bold.
Highcharts code:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>My first column chart by Highcharts</title>
<!-- 1. Add JQuery and Highcharts in the head of your page -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<!-- 2. You can add print and export feature by adding this line -->
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<!-- 3. Add the JavaScript with the Highchart options to initialize the chart -->
<script type="text/javascript">
jQuery(document).ready(function() {
var options = {
chart: {
renderTo: 'container',
**type: 'line'**
},
title: {
text: 'Tiny Tool Monthly Sales'
},
subtitle: {
text: '2014 Q1-Q2'
},
xAxis: {
categories: []
},
yAxis: {
title: {
text: 'Sales'
}
},
series: []
};
// JQuery function to process the csv data
$.get(**'column-data.csv'**, function(data) {
// Split the lines
var lines = data.split('\n');
$.each(lines, function(lineNo, line) {
var items = line.split(',');
// header line contains names of categories
if (lineNo == 0) {
$.each(items, function(itemNo, item) {
//skip first item of first line
if (itemNo > 0) options.xAxis.categories.push(item);
});
}
// the rest of the lines contain data with their name in the first position
else {
var series = {
data: []
};
$.each(items, function(itemNo, item) {
if (itemNo == 0) {
series.name = item;
} else {
series.data.push(parseFloat(item));
}
});
options.series.push(series);
}
});
//putting all together and create the chart
var chart = new Highcharts.Chart(options);
});
});
</script>
</head>
<body>
<!-- 3. Add the container -->
<div id="container" style="width: 600px; height: 400px; margin: 0 auto"></div>
</body>
</html>

jquery ui datepicker not working with tabs

When a user switches tabs in the jquery ui code they can click on a button to add data to a jqgrid. The only thing that is not working is datepicker; it will launch one time and after that when switching to a new tab it will not launch again.
source document code;
<link href="/Includes/Site.css" rel="stylesheet" type="text/css">
<link rel="stylesheet" type="text/css" href="/Includes/jqgrid/css/jquery-ui.css">
<link rel="stylesheet" type="text/css" href="/Includes/jqgrid/src/css/ui.jqgrid.css">
<script src="/Includes/jqgrid/js/jquery-2.1.4.min.js"></script>
<script src="/Includes/jqgrid/css/jquery-ui-1.11.4.min.js"></script>
<script src="/Includes/jqgrid/js/i18n/grid.locale-en.js"></script>
<script src="/Includes/jqgrid/js/jquery.jqGrid.min.js"></script>
<script src="/Includes/validation/dist/jquery.validate.min.js"></script>
<script src="/Includes/validation/dist/additional-methods.min.js"></script>
$("#tabs").tabs(
{
//each tab activation
activate:function(event, ui)
{ loadGrid(); },
beforeActivate:function(event, ui)
{
var curTab = $('#tabs .ui-tabs-active');
var curTabName = curTab.text();
var pos = curTabName.search('-');
var curID = curTabName.slice(0,pos);
var passFrmDiv = "div[id^=adddaydata" + curID + "]";
$(passFrmDiv).html("");
}
});
function loadGrid()
{
var curTab = $('#tabs .ui-tabs-active');
var curTabName = curTab.text();
var pos = curTabName.search('-');
var newID = curTabName.slice(0,pos);
//reset adddaydata
$("div[id^=adddaydata" + newID + "]").text('');
//load form
var getFrmURL = '90daywellform.php?id=' + newID + '&d=' + $.now();
var passFrmDiv = "div[id=wellform" + newID +"]";
$.get(getFrmURL, function(data)
{ $(passFrmDiv).html(data); });
//$(passFrmDiv).load('90daywellform.php?id=' + newID + ' #loadform');
//load grid
var getGrdURL = '90daygrid.php?id=' + newID + '&d=' + $.now();
var passGrdDiv = "div[id=jqgrid" + newID +"]";
$.get(getGrdURL, function(data)
{ $(passGrdDiv).html(data); });
//$(passGrdDiv).load('90daygrid.php?id=' + newID);
};
//date picker function for adding wells info
$("button[id^=addday]").click(function()
{
var curTab = $('#tabs .ui-tabs-active');
var curTabName = curTab.text();
var pos = curTabName.search('-');
var newID = curTabName.slice(0,pos); //id of the current well
//var dtTag = '#datepicker' + newID;
$.get('get90maxday.php?id=' + newID,
function(data)
{
var passMax = data;
var getFrmURL = '90dayadddayform.php?id=' + newID + '&maxday=' + passMax + '&d=' + $.now();
var passFrmDiv = "div[id^=adddaydata" + newID + "]";
$.get(getFrmURL, function(data)
{ $(passFrmDiv).html(data); });
//$().text(newID + " " + passAPI);
//$("#gridarea").load('scadagrid.php?api=' + passAPI + '&start=' + passStart + '&end=' + passEnd);
}
);
});
And here is the code from the dynamic document that is being loaded;
<?php
$id = $_GET['id'];
?>
<link href="/Includes/Site.css" rel="stylesheet" type="text/css">
<link rel="stylesheet" type="text/css" href="/Includes/jqgrid/css/jquery-ui.css">
<script src="/Includes/jqgrid/js/jquery-2.1.4.min.js"></script>
<script src="/Includes/jqgrid/css/jquery-ui-1.11.4.min.js"></script>
<script src="/Includes/validation/dist/jquery.validate.min.js"></script>
<script src="/Includes/validation/dist/additional-methods.min.js"></script>
<tr>
<td><label for="dt<?php echo $id; ?>">Date</label></td>
<td><input id="dt<?php echo $id; ?>" name="dt<?php echo $id;?>" type="text"></td>
</tr>
var passID = $("input[id^=id]").val();
var dtPkr = "input[id=dt" + passID +"]";
$(dtPkr).datepicker();
Any assistance is greatly appreciated
You're going to want to tap into the activate event if you've got this hosted in a tab (don't see it in the code, but it's in the question?). See jQuery UI Tabs Widget documentation.
You're going to want to add, in activate or in your loadGrid() function, something to initialize the datepickers:
$(".datepicker").datepicker();
You would, of course, have to have the datepickers be of class datepicker for that to work. See jQuery UI Datepicker documentation.

Categories