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

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.

Related

Configuring jqgrid search to search one of many

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.

Execute validation with button

I'm looking to execute the Handsontable validation on the click of a button instead of on cell change. Something like this: validateCells() (return bool isValid). This function doesn't seem to be working for me.
var
data = [],
container = document.getElementById('hot-Handsontable'),
save = document.getElementById('save'),
hidden = document.getElementById('hot-Handsontable-value'),
hot,
hotIsValid = true,
emailValidator;
emptyValidator = function(value, callback) {
callback(false);
};
hot = Handsontable(container, {
data: data,
minRows: 1,
minCols: 21,
maxCols: 21,
minSpareRows: 1,
stretchH: 'all',
colHeaders: ['Test'],
columns: [{data:'Test',allowInvalid:true, validator: emptyValidator}]
});
// exclude empty rows from validation
$('.title-block .united-alert a[href^=#Handsontable]').click(function() {
var href = $(this).attr('href');
var row = href.getIdIndex();
var prop = /([^__]*)$/.exec(href)[0];
hot.selectCellByProp(parseInt(row), prop);
return false;
});
// Save event
Handsontable.Dom.addEvent(save, 'click', function(e) {
var test = hot.validateCells(); // test is undefined
if (hotIsValid === true) {
hidden.value = JSON.stringify(hot.getData());
} else {
e.preventDefault();
}
});
What you should be doing, instead of var test = hot.validateCells() is the following:
// Save event
Handsontable.Dom.addEvent(save, 'click', function(e) {
hot.validateCells(function(hotIsValid) {
if (hotIsValid === true) {
hidden.value = JSON.stringify(hot.getData());
} else {
e.preventDefault();
}
})
});
Notice that validateCells takes a callback and returns undefined. This is why you see test as undefined. One other thing to note is that the callback is executed for every cell in your table so be careful with it.

Marionette drop in new ItemView after every fetch not working

I am working with an app that after every collection.fetch, I need to drop in a random ad into the DOM. But, every time the collection fetches, and the ad is dropped in, it appears that the DOM is resetting itself instead of just appending new items to the overall collection container.
Here is the ItemView for the ad:
define(["marionette", "lodash", "text!ads/template.html", "eventer"],
function(Marionette, _, templateHTML, eventer) {
'use strict';
var AdsView = Marionette.ItemView.extend({
template: _.template(templateHTML),
ui: {
ad: '.ad'
},
initialize: function() {
this.listenTo(eventer, 'generate:new:ad', this.generateNewAd, this);
},
onShow: function() {
// Set add image onShow
this.ui.ad.prop('src', '/ad/' + this.randomNumber());
},
generateNewAd: function(childView) {
var newAd = this.ui.ad.clone(),
element = childView.$el,
elementId = childView.model.get("id");
newAd.prop('src', '/ad/' + this.randomNumber());
$("#" + elementId).after(newAd);
},
randomNumber: function() {
return Math.floor(Math.random()*1000);
},
setUpAd: function() {
this.ui.ad.prop('src', '/ad/' + this.randomNumber());
}
});
return AdsView;
});
CompositeView that holds the Products (I'm calling for a new ad after the collection is done syncing):
define(["marionette", "lodash", "text!fonts/products/template.html",
'fonts/products/item-view', 'fonts/products/model', 'eventer'],
function(Marionette, _, templateHTML, ProductItemView, ProductsModel, eventer) {
'use strict';
var ProductsView = Marionette.CompositeView.extend({
template: _.template(templateHTML),
childView: ProductItemView,
childViewContainer: '.items',
productsLimit: 150,
initialize: function() {
this.listenTo(eventer, 'sort:products', this.sortCollection, this);
this.listenTo(this.collection, 'sync', this.setupSync, this);
},
sortCollection: function(field) {
this.collection.sortByKey(field);
},
setupSync: function() {
this.setupWindowScrollListener();
this.adGeneration();
},
adGeneration: function() {
var child = this.children.last();
eventer.trigger('generate:new:ad', child);
},
productsEnd: function() {
eventer.trigger('products:end');
},
setupWindowScrollListener: function() {
var $window = $(window),
$document = $(document),
that = this,
collectionSize = that.collection.length;
if(collectionSize <= that.productsLimit) {
$window.on('scroll', _.throttle(function() {
var scrollTop = $window.scrollTop(),
wHeight = $window.height(),
dHeight = $document.height(),
margin = 200;
if(scrollTop + wHeight > dHeight - margin) {
eventer.trigger('fetch:more:products');
$window.off('scroll');
}
}, 500));
} else {
that.productsEnd();
}
},
});
return ProductsView;
});
From your previous question I noticed that you're passing { reorderOnSort: false } to your ProductsView. This will cause your CompositeView to re-render on a sort event. Since a 'sort' event is triggered by Collection.set(), you'll have to pass { reorderOnSort: true } to ensure that your CompositeView is not re-rendered after a fetch → set → sort.
Note: If your CompositeView defines a filter method and the children are filter'ed when new models are fetched, the CompositeView will re-render.

Marionette CompositeView children.findByIndex not working as expected after collection sync

I have the following code that happens after a collection sync:
adGeneration: function() {
var child = this.children.findByIndex(this.children.length - 1);
console.log(child.model.toJSON());
eventer.trigger('generate:new:ad', child);
},
The problem I am running into, is that, after the first sync, the child element is a blank model:
First Time:
Object {id: "5-vp39kv3uiigxecdi", size: 26, price: "9.84", face: "( ⚆ _ ⚆ )"}
Every time after:
Object {length: 40, models: Array[41], _byId: Object, _listeningTo: Object, _listenId: "l14"…}
ProductsCollection
define(["backbone", "lodash", "fonts/products/model", "eventer"],
function(Backbone, _, ProductModel, eventer) {
'use strict';
var ProductsCollection = Backbone.Collection.extend({
model: ProductModel,
sort_key: 'price',
url: '/api/products',
offset: 0,
initialize: function() {
this.listenTo(eventer, 'fetch:more:products', this.loadMore, this);
},
comparator: function(item) {
return item.get(this.sort_key);
},
sortByKey: function(field) {
this.sort_key = field;
this.sort();
},
parse: function(data) {
return _.chain(data)
.filter(function(item) {
if(item.id) {
return item;
}
})
.map(function(item){
item.price = this.formatCurrency(item.price);
return item;
}.bind(this))
.value();
},
formatCurrency: function(total) {
return (total/100).toFixed(2);
},
loadMore: function() {
this.offset += 1;
this.fetch({
data: {
limit: 20,
skip: this.offset
},
remove: false,
success: function(collection) {
this.add(collection);
}.bind(this)
});
}
});
return ProductsCollection;
});
LayoutView that contains the View for the productions collection. The collection is fetched onShow of the layoutview
define(["marionette", "lodash", "text!fonts/template.html",
"fonts/controls/view", "fonts/products/view", "fonts/products/collection", "eventer"],
function(Marionette, _, templateHTML, ControlsView, ProductsView,
ProductsCollection, eventer) {
'use strict';
var FontsView = Marionette.LayoutView.extend({
regions: {
controls: '#controls',
products: '#products-list'
},
template: _.template(templateHTML),
initialize: function() {
this._controlsView = new ControlsView();
this._productsView = new ProductsView({
collection: new ProductsCollection({
reorderOnSort: false,
sort: false
})
});
this.listenTo(this._productsView.collection, 'sync', this.loading, this);
this.listenTo(eventer, 'fetch:more:products', this.loading, this);
this.listenTo(eventer, 'products:end', this.productsEnd, this);
},
onRender: function() {
this.getRegion('controls').show(this._controlsView);
this.getRegion('products').show(this._productsView);
this.loading();
},
onShow: function() {
this._productsView.collection.fetch({
data: {
limit: 20
}
})
},
productsEnd: function() {
this.loading();
this.$el.find('#loading').html("~ end of catalogue ~")
},
loading: function() {
var toggle = this.$el.find('#loading').is(':hidden');
this.$el.find('#loading').toggle(toggle);
}
});
return FontsView;
});
AdsView:
define(["marionette", "lodash", "text!ads/template.html", "eventer"],
function(Marionette, _, templateHTML, eventer) {
'use strict';
var AdsView = Marionette.ItemView.extend({
template: _.template(templateHTML),
ui: {
ad: '.ad'
},
initialize: function() {
this.listenTo(eventer, 'generate:new:ad', this.generateNewAd, this);
},
onShow: function() {
// Set add image onShow
this.ui.ad.prop('src', '/ad/' + this.randomNumber());
},
generateNewAd: function(childView) {
var newAd = this.ui.ad.clone(),
element = childView.$el,
elementId = childView.model.get("id");
newAd.prop('src', '/ad/' + this.randomNumber());
$("#" + elementId).after(newAd);
},
randomNumber: function() {
return Math.floor(Math.random()*1000);
},
setUpAd: function() {
this.ui.ad.prop('src', '/ad/' + this.randomNumber());
}
});
return AdsView;
});
I think your problem is in the ProductsCollection.loadMore method. There, in the success callback to your fetch you do,
function(collection) { this.add(collection); }
What's happening behind the scenes is that before your success callback is invoked, Backbone will first run Collection.set() on your data. By default, inside set your data will be parsed into a array of models returned by ProductsCollection.parse and if any new models are found they will be add'ed to your existing collection (note that unless you pass { remove: false } to your fetch options, models in your collection which are not in your last fetch will be removed. See Collection.set)
So, what happens when you do the fetch in loadMore, which is called after the first fetch, Backbone will first add all the models from the server (that are returned from ProductsCollection.parse) and then invoke the success callback of your fetch, which, essentially does one last add. And what it's add'ing is the ProductsCollection instance. Not collection.models, an array of models, rather a Backbone object that has a property models that holds a raw array of models. Hence, the strange output:
Object {length: 40, models: Array[41], _byId: Object, _listeningTo: Object,
_listenId: "l14"…}
Simply remove that success callback (which is unnecessary) and the last child view of your ProductsView should be the view rendered from the last model returned.

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

Resources