Configuring jqgrid search to search one of many - jqgrid

I'm having trouble either understanding or implementing search/filter functionality in jqgrid.
The data set is returned to the client with each item having a list of designers:
"IAConsultWorkflowRequestsList": [
{
"AppID": "ISP",
"SubmittedDate": "12/13/2018",
"IAAssigned": "<a style='color:blue !important;' href='mailto:Joseph#somewhere.com'><u>Joseph Kraft</u></a>",
"IAAssignedName": null,
"Status": "In Discovery",
"SLA": 0,
"DaysPassed": 157,
"IsUserFM": false,
"IsUserSecureEnv": false,
"DesignParticipants": [
{
"Name": "John Kraft",
"EmailAddress": "",
"ID": "A2049"
},
{
"Name": "Zack Adamas",
"EmailAddress": "Zachary.Adamas#somewhere.com",
"ID": "U6696"
},
{
"Name": "David Kosov",
"EmailAddress": "David.Kosov#somewhere.com",
"ID": "U6644"
}
]
}
So in the 'Designers' column, I am concatenating the results to be comma separated, e.g.
John Kraft,
Zack Adamas,
David Kosov
And, if the item has an email address, the individual name is formatted as an email link:
<td role="gridcell" style="text-align:center;" title="John Kraft,Zack Burns,David Cosand" aria-describedby="workFlowIAGrid_DesignParticipants">
John Kraft,<br>
<a style="color:blue !important;" ref="mailto:Zachary#somewhere.com"><u>Zack </u></a>,<br>
<a style="color:blue !important;" href="mailto:David#somewhere.com"><u>David </u></a></td>
I have a select element with entries John, Zack, and David, but when I select one of the options, I do not get expected results. If I select David, I would like to be shown any rows that contain David as one of potentially several names in the Designer column.
However, I am getting erratic behavior. Some of the sopt options will cause something to happen, but not what is expected. None of the contains/not contained or in/not in options seem to do what I need. What am I doing wrong?
Per Tony's comment, here is the grid init code:
$gridEl.jqGrid({
xhrFields: {
cors: false
},
url: "/IAConsult/GetWorkFlowIARequests",
postData: {
showAll: showAllVal,
role: role,
IsIAArchitect: userIsIA
},
datatype: "json",
crossDomain: true,
loadonce: true,
mtype: 'GET',
sortable: true,
viewrecords: true,
pager: '#workFlowIAGridPager',
multiselect: true,
rowNum: 50,
autowidth: true,
colModel: [
{ label: 'Design Participants', name: 'DesignParticipants', align: "center", formatter:commaSeparatedList },
//same for other columns...
],
beforeSelectRow: function (rowid, e) {
var $myGrid = $(this),
i = $.jgrid.getCellIndex($(e.target).closest('td')[0]),
cm = $myGrid.jqGrid('getGridParam', 'colModel');
return (cm[i].name === 'cb');
},
jsonReader: {
repeatitems: true,
root: "IAConsultWorkflowRequestsList"
},
beforeSubmitCell: function (rowid, name, value, iRow, iCol) {
return {
gridData: gridData
};
},
serializeCellData: function (postdata) {
return JSON.stringify(postdata);
},
gridComplete: function () {
rowCount = $gridEl.getGridParam('records');
gridViewRowCount = rowCount;
var rowIDs = $gridEl.getDataIDs();
var inCompleteFlag = false;
//Filter code to apply filter in headers in MyWork grid
var datatoFilter = $gridEl.jqGrid('getGridParam', 'lastSelectedData').length == 0
? $gridEl.jqGrid("getGridParam", "data")
: $gridEl.jqGrid('getGridParam', 'lastSelectedData');
var $grid = $gridEl, postfilt = "";
var getUniqueNames = function (columnName) {
var uniqueTexts = [],
mydata = datatoFilter,
texts = $.map(mydata, function(item) {
return item[columnName];
}),
textsLength = texts.length,
text = "",
textsMap = {},
i;
if (texts[0] && texts[0].Name)
texts = $.map(texts,
function(item) {
return item.Name;
});
for (i = 0; i < textsLength; i++) {
text = texts[i];
if (text !== undefined && textsMap[text] === undefined) {
// to test whether the texts is unique we place it in the map.
textsMap[text] = true;
uniqueTexts.push(text);
}
}
if (columnName == 'ConsultID') {
return (uniqueTexts.sort(function (a, b) { return a - b; }));
} else return uniqueTexts.sort();
}, buildSearchSelect = function (uniqueNames) {
var values = {};
values[''] = 'All';
$.each(uniqueNames,
function () {
values[this] = this;
});
return values;
}, setSearchSelect = function (columnName) {
var changedColumns = [];
this.jqGrid("setColProp",
columnName,
{
stype: "select",
searchoptions: {
value: buildSearchSelect(getUniqueNames.call(this, columnName)),
sopt: getSortOptionsByColName(columnName),
dataEvents: [
{
type: "change",
fn: function (e) {
setTimeout(function () {
//get values of dropdowns
var DesignParticipant = $('#gs_workFlowIAGrid_DesignParticipants').val();
//same for other columns...
var columnNamesArr = columns.split(',');
changedColumns.push(columnName);
for (i = 0; i < columnNamesArr.length; i++) {
if (true) {
var htmlForSelect = '<option value="">All</option>';
var un = getUniqueNames(columnNamesArr[i]);
var $select = $("select[id='gs_workFlowIAGrid_" + columnNamesArr[i] + "']");
for (j = 0; j < un.length; j++) {
var val = un[j];
htmlForSelect += '<option value="' + val + '">' + val + '</option>';
}
$select.find('option').remove().end().append(htmlForSelect);
}
}
$('#gs_workFlowIAGrid_DesignParticipants').val(DesignParticipant);
//same for other columns...
},
500);
//setting the values :
}
}
]
}
});
};
function getSortOptionsByColName(colName) {
console.log(colName);
if (colName === 'DesignParticipants')
return ['in'];
else
return ['eq'];
}
setSearchSelect.call($grid, "DesignParticipants");
//same for other columns...
$grid.jqGrid("filterToolbar",
{ stringResult: true, searchOnEnter: true });
var localFilter = $gridEl.jqGrid('getGridParam', 'postData').filters;
if (localFilter !== "" && localFilter != undefined) {
globalFilter = localFilter;
}
$gridEl.jqGrid("setGridParam",
{
postData: {
"filters": globalFilter,
showAll: showAllVal,
role: role,
IsIAArchitect: userIsIA
},
search: true,
forceClientSorting: true
})
.trigger("reloadGrid");
//Ending Filter code
var columnNamesArr = columns.split(',');
for (i = 0; i < columnNamesArr.length; i++) {
if (true) {
var htmlForSelect = '<option value="">All</option>';
var un = getUniqueNames(columnNamesArr[i]);
var $select = $("select[id='gs_workFlowIAGrid_" + columnNamesArr[i] + "']");
for (j = 0; j < un.length; j++) {
val = un[j];
htmlForSelect += '<option value="' + val + '">' + val + '</option>';
}
$select.find('option').remove().end().append(htmlForSelect);
}
}
},
// all grid parameters and additionally the following
loadComplete: function () {
$gridEl.jqGrid('setGridWidth', $(window).width(), true);
$gridEl.setGridWidth(window.innerWidth - 20);
},
height: '100%'
});
Here is the formatter I am using on the column:
function commaSeparatedList(cellValue, options, rowdata, action) {
let dps = [];
_.forEach(cellValue, function (item) {
let formatted = '';
if (item.EmailAddress)
formatted += '<a style="color:blue !important;" href="mailto:' +
item.EmailAddress +
'"><u>' +
item.Name +
'</u></a>';
else formatted = item.Name;
dps.push(formatted + ',<br/>');
});
let toString = dps.join('');
return toString.substring(0,toString.length-6);
}
And then the only other pertinent thing is that I used a function to return 'in' (or some other key - these are the options I said weren't apparently working in the initial post) if the column is named 'Design Participants', else equal for any other column:
setSearchSelect = function (columnName) {
var changedColumns = [];
this.jqGrid("setColProp",
columnName,
{
stype: "select",
searchoptions: {
value: buildSearchSelect(getUniqueNames.call(this, columnName)),
sopt: getSortOptionsByColName(columnName),
dataEvents: [
{...
function getSortOptionsByColName(colName) {
console.log(colName);
if (colName === 'DesignParticipants')
return ['in'];
else
return ['eq'];
}

The issue was that the underlying data (the DesignParticipants in the returned JSON above) did not match the selected string, since the data itself was an array. I believed the filtering was based on the displayed text in the grid table, but, it was based on the underlying data. So, I created a new property of the returned JSON that was a string, and the filtering worked as expected.

Related

Using server side true, datatables column search not working, but the global search works

I'm using datatables with server-side attribute true, the search work on global search, but not when I'm using column search. There isn't any error, the table is redrawn but the search not applied.
//index.blade.php
<script>
$('#filter-time-slot-submit').on('click', function() {
var table = $('#hide_show_column').DataTable({
'retrieve': true,
});
var timeSlot = $('#select2-chosen-2').text();
table
.columns(3)
.search(timeSlot)
.draw();
});
</script>
//table-advanced.js
var TableAdvanced = function () {
var initHideShowColumn = function () {
var table = $('#hide_show_column');
var tableWrapper = $('#hide_show_column_wrapper'); // datatable creates the table wrapper by adding with id {your_table_jd}_wrapper
var tableColumnToggler = $('#hide_show_column_column_toggler');
var tableHeaderRow = $('#table-header-row');
var columns = [];
var colName;
var ajaxUrl;
$('input[type="checkbox"]', tableColumnToggler).each(function(index, el) {
colName = $(el).attr('data-name');
columns.push({
"name": colName
});
$(el).attr("data-column", index);
if (colName.indexOf('.') > 0) {
colName = colName.substring(0, colName.indexOf('.'));
}
tableHeaderRow.append($('<th class="filter_' + colName + ' text-center">' + $(el).parent().parent().parent().text() + '</th>'));
});
columns.push({"name": ""});
tableHeaderRow.append($('<th class="text-center">Action</th>'));
if (typeof table.attr('data-url') !== 'undefined') {
ajaxUrl = table.data('url');
} else {
ajaxUrl = window.location.href;
}
table.on('init.dt', function () {
Index.init();
});
table.on('draw.dt', function () {
Index.draw();
});
var oTable = table.DataTable({
// Internationalisation. For more info refer to http://datatables.net/manual/i18n
"language": {
"aria": {
"sortAscending": ": activate to sort column ascending",
"sortDescending": ": activate to sort column descending"
},
"emptyTable": "No data available in table",
"info": "Showing _START_ to _END_ of _TOTAL_ entries",
"infoEmpty": "No entries found",
"infoFiltered": "(filtered from _MAX_ total entries)",
"lengthMenu": "Show _MENU_ entries",
"search": "Search:",
"zeroRecords": "No matching records found"
},
"columnDefs": [{
"orderable": false,
"targets": [-1]
}],
"columns": columns,
"aaSorting": [],
"lengthMenu": [
[10, 25, 50, 100, 250, 500, 1000, -1],
[10, 25, 50, 100, 250, 500, 1000, "All"] // change per page values here
],
"serverSide": true,
"processing": true,
"ajax": {
"url": ajaxUrl
}
});
/* modify datatable control inputs */
tableWrapper.find('.dataTables_length select').select2(); // initialize select2 dropdown
/* init hidden column*/
$('input[type="checkbox"]', tableColumnToggler).each(function(index, el) {
var checked = el.checked;
if (!checked) {
var column = oTable.column(index);
column.visible( ! column.visible() );
}
});
/* handle show/hide columns*/
$('input[type="checkbox"]', tableColumnToggler).change(function () {
/* Get the DataTables object again - this is not a recreation, just a get of the object */
var column = oTable.column($(this).attr("data-column"));
column.visible( ! column.visible() );
});
$('.form-filter-submit').on('click', function (e) {
e.preventDefault();
submitFilter(oTable);
});
$('.form-filter-reset').on('click', function (e) {
e.preventDefault();
resetFilter(oTable);
});
}
function submitFilter(table) {
var query = [];
var filterColumn;
var filterValue;
// get all typeable inputs
$('textarea.form-filter, select.form-filter, input.form-filter:not([type="radio"],[type="checkbox"])').each(function() {
if ($(this).val()) {
filterColumn = '__' + $(this).attr('name');
filterValue = $(this).val();
query.push(filterColumn + '=' + filterValue);
}
});
// // get all checkboxes
// $('input.form-filter[type="checkbox"]:checked', table).each(function() {
// the.addAjaxParam($(this).attr("name"), $(this).val());
// });
// // get all radio buttons
// $('input.form-filter[type="radio"]:checked', table).each(function() {
// the.setAjaxParam($(this).attr("name"), $(this).val());
// });
table.settings().ajax.url('?'+query.join('&'));
table.ajax.reload();
}
function resetFilter(table) {
table.settings().ajax.url(window.location.href).load();
}
return {
//main function to initiate the module
init: function () {
if (!jQuery().dataTable) {
return;
}
initHideShowColumn();
}
};
}();
I expect the table should be filtered by the search when I click a button, but the table shows all the data.
Any help will be greatly appreciated. Thank You.

JsGrid Sorting not working

Following is part of my JsGrid code, which I think something is missing in order for me to sort my data like any other examples on Fiddle.
autoload: true,
inserting: false,
editing: false,
paging: true,
pageIndex: 1,
pageSize: 5,
pageLoading: true,
autoload: true,
filter: true,
sorting: true,
controller: {
loadData: function(filter) {
return $.ajax({
type: "GET",
url: BASE_URL,
data: filter,
dataType: "json",
cache: false
});
},
},
I have tried with sorting:"number".
Below logic of sorting on the basis of number
$("#Grid2").jsGrid({
height: "auto",
width: "100%",
filtering: false,
editing: false,
sorting: true,
paging: true,
autoload: true,
inserting: false,
pageSize: 15,
pageButtonCount: 5,
controller: {
loadData: function(filter) {
var d = $.Deferred();
$.ajax({
cache: false,
type: 'GET',
url: "http://" + servername + ":" + portnumber + "/api,
data: filter,
dataType: "json",
success: function(data) {
filteredData = $.grep(data, function(item) {
//filtering logic
;
});
d.resolve(filteredData);
testdata = JSON.stringify(data);
$("#Grid2").jsGrid("sort", 1);
HistoricData = data;
},
error: function(e) {
console.log(e);
console.log(e.responseText);
var errorMsg = e.responseText;
var msg = errorMsg + " for this particular combination";
showError(msg);
$("#displayingHistoryValues").hide();
$("#ExportGrid2").hide();
$("#Grid2").hide();
d.resolve();
}
});
return d.promise();
}
},
fields: [{
title: "Value",
name: "MeasureValue",
type: "number",
width: "5%",
css: "custom-field",
sorting: true,
itemTemplate: function(value, item) {
if (item.MeasureValue != null && item.MeasureValue != '' && item.MeasureValue.trim().length > 0) {
var mesval = FormatValeur(item.MeasureUnit, item.MeasureValue);
return "<div>" + mesval + "</div>";
}
}
}, {
type: "control",
editButton: false,
deleteButton: false,
width: "5%"
}]
})
Another way to sort, get the filteredData or loaded data
and call onRefresing of JSGrid .
Way to sort JS grid on column after grid load :
onRefreshing: function (args) {
fundCodeList = [];
jsonNumLst = [];
jsonNANLst = [];
if(this._visibleFieldIndex(this._sortField) == -1
|| this._visibleFieldIndex(this._sortField)==1){
$.each(filteredData, function(inx, obj) {
if($.isNumeric(obj.fundCode)){
jsonNumLst.push(obj);
}else{
jsonNANLst.push(obj);
}
});
if(this._sortOrder == undefined || this._sortOrder == 'asc'){
jsonNumLst.sort(sortByNumFCAsc);
jsonNANLst.sort(sortByNANFCAsc);
}else if(this._sortOrder == 'desc'){
jsonNANLst.sort(sortByNANFCDesc);
jsonNumLst.sort(sortByNumFCDesc);
}
if(jsonNumLst.length>0 || jsonNANLst.length>0){
filteredData = [];
if(this._sortOrder == undefined || this._sortOrder == 'asc'){
$.each(jsonNumLst, function(inx, obj) {
filteredData.push(obj);
});
if(filteredData.length == jsonNumLst.length){
$.each(jsonNANLst, function(inx, obj) {
filteredData.push(obj);
});
}
}else if(this._sortOrder == 'desc'){
$.each(jsonNANLst, function(inx, obj) {
filteredData.push(obj);
});
if(filteredData.length == jsonNANLst.length){
$.each(jsonNumLst, function(inx, obj) {
filteredData.push(obj);
});
}
}
}
if((filteredData.length>0) && filteredData.length==(jsonNumLst.length+jsonNANLst.length)){
$("#measureImportGrid3").data("JSGrid").data = filteredData;
//isSortGrid = false;
//saveEffectControlData = $('#saveEffectiveControlGrid').jsGrid('option', 'data');
}
}
//Ascending order numeric
function sortByNumFCAsc(x,y) {
return x.fundCode - y.fundCode;
}
//Ascending order nonnumeric
function sortByNANFCAsc(x,y) {
return ((x.fundCode == y.fundCode) ? 0 : ((x.fundCode > y.fundCode) ? 1 : -1 ));
}
//Descending order numeric
function sortByNANFCDesc(x,y) {
return ((x.fundCode == y.fundCode) ? 0 : ((y.fundCode > x.fundCode) ? 1 : -1 ));
}
//Descending order non-numeric
function sortByNumFCDesc(x,y) {
return y.fundCode - x.fundCode;
}
}

Jqgrid with mvc4

I want to create dynamic Jqgrid at runtime. I have made tow methods as
public ActionResult getdata( List<UserModel> lst)
{
UserModel usermodel = new UserModel();
UserService uservice = new UserService();
//return View(db.VideoModels.OrderByDescending(v => v.VideoId).ToPagedList(page, 3));
string[] columnNames = (string[])TempData["columnname"];
lst = new List<UserModel>();
lst = uservice.GetAllUsers();
JavaScriptSerializer serializer = new JavaScriptSerializer();
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> row;
foreach (var dr in lst)
{
row = new Dictionary<string, object>();
rows.Add(row);
}
return Json(serializer.Serialize(lst), JsonRequestBehavior.AllowGet);
}
public ActionResult GetColumnDetails( List<UserModel> lst)
{
UserModel usermodel = new UserModel();
UserService uservice = new UserService();
lst = new List<UserModel>();
lst = uservice.GetAllUsers();
var listOfStrings = new List<string>();
string[] colNames = listOfStrings.ToArray();
string[] columnNames = (from t in typeof(PrTblUsers).GetProperties() select t.Name).ToArray();
JavaScriptSerializer serializer = new JavaScriptSerializer();
return Json(serializer.Serialize(colNames= columnNames), JsonRequestBehavior.AllowGet);
}
getcolumdetail is for getting column name and get data is for getting data.
div class="row">
<div id="content" style="margin-left:15px !important;">
<table id="datacopyProject"></table>
<div id="datacopy_pagerProject"></div>
#*<table id="datacopyfilter"></table>
<div id="datacopy_pagerfilter"></div>*#
</div>
</div>
<script type="text/javascript" id="getdata">
$(document).ready(function () {
var item = [];
//creating the dyanamic colmodel
$("#datacopyProject").jqGrid('GridUnload');
$.ajax(
{
type: "POST",
url: '/Test/GetColumnDetails',
//data: { tid: data },
dataType: "json",
success: function (result) {
var colModels = BuildColumnModel(JSON.parse(result));
//console.log(JSON.stringify(result));
//var obj = jQuery.parseJSON(result);
//var columnData = result.mypage,
item= getData();
//alert(item);
jQuery("#datacopyProject").jqGrid({
colNames: item,
colModel: colModels,
autowidth:true,
caption: "User List",
pager: jQuery('#datacopy_pagerProject'),
rowNum: 3,
viewrecords: true,
rowList: [5, 10, 20, 50],
viewrecords: true,
jsonReader: {
repeatitems: false,
root: function (obj) { return obj; },
page: function (obj) { return $("#datacopyProject").jqGrid('getGridParam', 'page'); },
total: function (obj) { return Math.ceil(obj.length / $("#datacopyProject").jqGrid('getGridParam', 'rowNum')); },
records: function (obj) { return obj.length; }
},
gridComplete: function () {
},
loadComplete: function (data) { }
})
},
loadonce:true,
error: function (x, e) {
alert(x.readyState + " " + x.status + " " + e.msg);
}
});
//setTimeout(function () { $("#datacopyProject").jqGrid('setGridParam', { datatype: 'json' }); }, 500);
//binding the data to dyanamic colmodel
function getData()
{
$.ajax({
url: '/Test/getdata',
type: "POST",
datatype: "json",
//data: { userid: data },
async: false,
success: function (response) {
var resultData = JSON.parse(response);
//var data = resultData.slice(1, resultData.length - 1);
//var json = JSON.stringify(data);
//console.log(resultData);
////var resultData = JSON.parse(response);
for (var i = 0; i <= resultData.length; i++)
item = $("#datacopyProject").jqGrid('addRowData', i + 1, datacopyProject[i]);
//$(resultData).each(function (e) {
// $("#datacopyProject").addRowData(e, this);
//});
}
});
}
});
function BuildColumnModel(result) {
debugger;
// var uFields = result.split(',');
var uFields = result;
var columns = [];
for (var i = 0; i < uFields.length ; i++) {
if (uFields[i].indexOf('Id') > -1) {
columns.push({ name: uFields[i], index: uFields[i], key: true });
//columns.push({ 'name': name, 'index': name, key: true});
}
// else if (uFields[i].indexOf('Name') > -1) {
else if (uFields[i].length > -1) {
columns.push({ name: uFields[i], index: uFields[i] })
// columns.push({ 'name': name, 'index': name });
}
//else if (uFields[i].length > -1) {
// columns.push({ name: uFields[i], index: uFields[i]})
// //columns.push({ 'name': name, 'index': name, key: true });
//}
}
return columns;
}
I am getting the column value in jQgrid but not getting the rows.
You can use the solution explained in this post, and return from the controller a ViewBag with these variables joined:
var jsonGrid = jQuery.parseJSON('#Html.Raw(ViewBag.YourGridVariableInJson)');

google maps and ajax

Is it possible to return a variable, more specifically an array of values or a string from an $.ajax call. I currently understand that this can't be done... i.e. $.ajax responses need to be added to the DOM immediately. Please correct me if I am missing something obvious here.
var infoWindow;
var tableID = 'atableID';
var str;
var beachID;
var beach_location;
var beach_region;
/* start map initialization */
function initialize() {
latlng = new google.maps.LatLng(49.894634, -97.119141);
var myOptions = {
center: latlng,
zoom: 7,
mapTypeId: google.maps.MapTypeId.ROADMAP,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.SMALL
},
mapTypeControl: true,
mapTypeControlOptions: {
mapTypeIds: [
google.maps.MapTypeId.ROADMAP,
google.maps.MapTypeId.SATELLITE,
google.maps.MapTypeId.HYBRID,
google.maps.MapTypeId.TERRAIN
],
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
},
overviewMapControl: true,
overviewMapControlOptions: {
opened: true
}
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
layer = new google.maps.FusionTablesLayer({
query: {
select: 'Point',
from: atableID
},
suppressInfoWindows: true
});
layer.setMap(map);
infoWindow = new google.maps.InfoWindow();
google.maps.event.addListener(layer, 'click', function (e) {
// close infoWindow if open
if (infoWindow) {
infoWindow.close();
}
beachID = e.row['Beach_ID'].value;
beach_location = e.row['Beach_Location'].value; ;
beach_region = e.row['Beach_Region'].value;;
//console.log(beachID);
// get data set
getEcoliData(beachID,beach_location,beach_region);
getAlgaeData(beachID,beach_location,beach_region);
}); // end google.maps.addListener
} // end map initialization
function getEcoliData(beachID,beach_location,beach_region) {
//local namespace
var rows = [];
var ecoliTable;
var items = [];
var queryURL = "https://www.googleapis.com/fusiontables/v1/query?sql=";
var queryTail = '&key=a key value=?';
var whereClause = "WHERE 'Beach_ID' = " + beachID;
var query = "SELECT 'Sample_Date', 'Average_E._coli_Density','Recreational_Water_Quality_Guideline' FROM atblid " + whereClause + " ORDER BY 'Sample_Date' DESC";
var queryText = encodeURI(query);
$.ajax({
type: "GET",
url: queryURL + queryText + queryTail,
cache: false,
dataType: 'jsonp',
success: function (data) {
rows = data.rows;
// empty table
//$('#content_placeholder').empty();
//$('.ecoli_table').remove();
$('#ecoli_heading').empty();
$('#content_placeholder').prepend('<h6 id="ecoli_heading">E.Coli Data</h6>')
.append('<p>' + beach_location + '</p>').append('<p>' + beach_region + '</p>');
$('.ecoli_table').append('<tr>'
+ '<th>Sample Date</th>'
+ '<th>Average E.Coli Density</th>'
+ '<th>Recreational Water Quality Guideline</th>'
+ '</tr>');
for (var i = 0; i < rows.length; i++) {
//items.push(rows[i]);
$('.ecoli_table tr:first').after('<tr><td>' + rows[i].join('</td><td>') + '</td></tr>');
}
if (typeof ecoliTable == 'undefined') {
// dataTables
ecoliTable = $(".ecoli_table").dataTable({
"sPaginationType": "full_numbers",
"aLengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]],
"aaSorting": [[0, "desc"]],
"bDestroy": true,
"aoColumns": [
{ "sTitle": "Sample_Date" },
{ "sTitle": "Average_E._coli_Density" },
{ "sTitle": "Recreational_Water_Quality_Guideline" }
]
});
} else {
//ecoliTable.fnDestroy();
$(".ecoli_table > tbody").empty();
ecoliTable.fnDraw();
//$('.ecoli_table').find("tr:gt(0)").remove();
}
},
error: function () {
alert("Data is not available for this location at the present time, please check back at a later time. Thank you.");
}
});
}
function getAlgaeData(beachID,beach_location,beach,region) {
//local namespace
var rows = [];
var algaeTable;
var items = [];
var queryURL = "https://www.googleapis.com/fusiontables/v1/query?sql=";
var queryTail = '&key=apikey&callback=?';
var whereClause = "WHERE 'Beach_ID' = " + beachID;
var query = "SELECT 'Sample_Date','Algal_Toxin_Microcystin','Recreational_Guideline_20','Blue_Green_Algae_Cells','Recreational_Guideline' FROM tableid " + whereClause + " ORDER BY 'Sample_Date' DESC";
var queryText = encodeURI(query);
$.ajax({
type: "GET",
url: queryURL + queryText + queryTail,
cache: false,
dataType: 'jsonp',
success: function (data) {
rows = data.rows;
// empty table
//$('#content_placeholder').empty();
//$('.algae_table').remove();
$('#algae_heading').empty();
$('.ecoli_table').after('<h6 id="algae_heading">Algae Data</h6>');
$('.algae_table').append('<tr>'
+ '<th>Sample Date</th>'
+ '<th>Algal_Toxin_Microcystin</th>'
+ '<th>Recreational_Guideline_20</th>'
+ '<th>Blue_Green_Algae_Cells</th>'
+ '<th>Recreational_Guideline</th>'
+ '</tr>');
for (var i = 0; i < rows.length; i++) {
//items.push(rows[i]);
$('.algae_table tr:first').after('<tr><td>' + rows[i].join('</td><td>') + '</td></tr>');
}
if (typeof algaeTable == 'undefined') {
//algae
algaeTable = $(".algae_table").dataTable({
"sPaginationType": "full_numbers",
"aLengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]],
"bDestroy": true,
"aaSorting": [[0, "desc"]],
"aoColumns": [
{ "sTitle": "Sample_Date" },
{ "sTitle": "Algal_Toxin_Microcystin" },
{ "sTitle": "Recreational_Guideline_20" },
{ "sTitle": "Blue_Green_Algae_Cells" },
{ "sTitle": "Recreational_Guideline" }
]
});
} else {
//algaeTable.fnDestroy();
$(".algae_table > tbody").empty();
algaeTable.fnDraw();
//$('.algae_table').find("tr:gt(0)").remove();
}
},
error: function () {
alert("Data is not available for this location at the present time, please check back at a later time. Thank you.");
}
});
}
I am trying to query 2 different Google Fusion tables and return each table under a new tab within a google infoWindow. However, I am running into issues because I can't seem to return an array or string from the $.ajax function to the parent scope. For example, the items array above returns undefined. Any thoughts around this is greatly appreciated.
Thanks in advance,
Michael
It is definitely possible. You haven't provided enough code to determine what's wrong, e.g. queryURL, queryText, etc. You'll need your Google API key as well. Here is an example demonstrating how to do it.
https://developers.google.com/fusiontables/docs/samples/basic_jsonp_request

Dynamic Columns in jqGrid

I've tried with limited success to get dynamic columns to work with jqGrid. Limited in that I can control the column names and formatting from the controller. But when I do this I can't get the data in.
Do you have a small sample solution that shows the controller code for the two calls.
you can actually bind the column as normal but you can show/hide them at runtime using jquery. for example i have to show link column in jqgrid for admin user and for normal users that column needs to be hidden so implement this in following way.
$("#grid").showCol("Link");
$("#grid").hideCol("Link");
$("#grid").trigger("reloadGrid");
JQGrid1.Columns.FromDataField(ColumnName).Visible = false;
JQGrid1.Columns.FromDataField(ColumnName).HeaderText = "Sample";
JQGrid(action, caption, 920, 400, loadtext);
function columnsData(Data) {
var str = "[";
for (var i = 0; i < Data.length; i++) {
str = str + "{name:'" + Data[i] + "', index:'" + Data[i] + "', editable: true}";
if (i != Data.length - 1) {
str = str + ",";
}
}
str = str + "]";
return str;
}
function JQGrid(action, caption, width, height, loadtext) {
var grid = $("#tblGrid");
var lastsel;
var editurl = '/PayInvoice/GridSave';
$.ajax({
url: action,
dataType: "json",
mtype: 'POST',
beforeSend: function () {
$("#dvloading").show();
},
success: function (result) {
if (result) {
if (!result.Error) {
var colData = columnsData(result.column);
colData = eval('{' + colData + '}');
grid.jqGrid('GridUnload');
grid.jqGrid({
url: action,
datatype: 'json',
mtype: 'POST',
colModel: colData,
colNames: result.column,
// multiselect: true,
width: width,
height: height,
rowNum: 20,
rowList: [20, 40, 60],
loadtext: loadtext,
pager: '#tblGridpager',
sortorder: "asc",
viewrecords: true,
gridview: true,
altRows: true,
cellEdit: true,
cellsubmit: "remote",
cellurl: '/PayInvoice/GridSavecell',
beforeSubmitCell: function (id, cellname, value, iRow, iCol) {
objedit(id, cellname, value);
return { id: id, cellname: cellname, value: value, iRow: iRow, iCol: iCol };
},
afterSaveCell: function (id, cellname, value, iRow, iCol) {
objedit(id, cellname, value);
return { id: id, cellname: cellname, value: value, iRow: iRow, iCol: iCol };
},
caption: caption
});
}
}
},
error: function (xhr, ajaxOptions, thrownError) {
if (xhr && thrownError) {
alert('Status: ' + xhr.status + ' Error: ' + thrownError);
}
}, complete: function () {
$("#dvloading").hide();
}
});
}
function objedit(id, cellname, value) {
var flag = 0;
for (var i = 0; i < index; i++) {
if (obj[i][0] == id && obj[i][1] == cellname) {
obj[i] = [id, cellname, value]
flag++;
}
}
if (flag == 0) {
obj[index] = [id, cellname, value];
index++;
}
}
Here we go;
$("#datagrid").jqGrid({
//url: "user.json",
//datatype: "json",
datatype: "local",
data: dataArray,
colNames:getColNames(dataArray[0]),
colModel:getColModels(dataArray[0]),
rowNum:100,
loadonce: true,
pager: '#navGrid',
sortname: 'SongId',
sortorder: "asc",
height: "auto", //210,
width:"auto",
viewrecords: true,
caption:"JQ GRID"
});
function getColNames(data) {
var keys = [];
for(var key in data) {
if (data.hasOwnProperty(key)) {
keys.push(key);
}
}
return keys;
}
function getColModels(data) {
var colNames= getColNames(data);
var colModelsArray = [];
for (var i = 0; i < colNames.length; i++) {
var str;
if (i === 0) {
str = {
name: colNames[i],
index:colNames[i],
key:true,
editable:true
};
} else {
str = {
name: colNames[i],
index:colNames[i],
editable:true
};
}
colModelsArray.push(str);
}
return colModelsArray;
}

Resources