Assign object from google scripts to local variable using AJAX - javascript

I wrote a custom Google Script which outputs an object for me and I would like to be able to call it and assign it to a variable which is then used to display data on a website.
HTML Header:
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>JQVMap - World Map</title>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<link href="../dist/jqvmap.css" media="screen" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script type="text/javascript" src="../dist/jquery.vmap.js"></script>
<script type="text/javascript" src="../dist/maps/jquery.vmap.world.js" charset="utf-8"></script>
<script type="text/javascript" src="js/jquery.vmap.sampledata.deaths.js"></script>
<script type="text/javascript" src="js/jquery.vmap.sampledata.infected.js"></script>
<script>
jQuery(document).ready(function () {
jQuery('#vmap').vectorMap({
map: 'world_en',
backgroundColor: '#333333',
color: '#ffffff',
hoverOpacity: 0.8,
selectedColor: '#3498DB',
enableZoom: true,
showTooltip: true,
scaleColors: ['#F3A291', '#FF4F3B'],
values: infected_data,
normalizeFunction: 'polynomial',
onLabelShow: function (event, label, code) {
label.html('<div class="map-tooltip"><h1 class="header"> ' + label.html() + '</h1><p class="description">Infected: ' + infected_data[code] + '</p><p class="description">Deaths: ' + death_data[code] + '</p></div>');
}
});
});
</script>
</head>
Google Scripts File:
function doGet() {
var result = {};
var infected = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Data').getDataRange().getValues();
var death = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Data').getDataRange().getValues();
result = makeObject(infected);
return ContentService.createTextOutput(JSON.stringify(result)).setMimeType(ContentService.MimeType.JSON);
}
function makeObject(multiArr) {
var obj = {};
var countrystats = {};
var headers = multiArr.shift();
for (var i = 0; i < headers.length; i++) {
countrystats[i] = multiArr.map(function (app) {
return app[i];
})
}
for (var m = 0; m < countrystats[1].length; m++) {
obj[countrystats[1][m]] = 0;
}
for (var j = 0; j < countrystats[1].length; j++) {
var TempVar;
TempVar = obj[countrystats[1][j]];
obj[countrystats[1][j]] = TempVar + countrystats[3][j];
}
return obj;
}
Google Scripts Output (using the JSON View chrome extension):
{
cn: 8134,
th: 23,
mo: 7,
us: 5,
jp: 11,
kr: 4,
sg: 10,
vn: 2,
fr: 5,
np: 1,
my: 8,
ca: 3,
ci: 1,
lk: 1,
au: 9,
de: 4,
fn: 1
}
This is a public link with the object/data i want on it (the same object shown above):web app: https://script.google.com/macros/s/AKfycbzsyQNJwDvQc5SvNGEDZZOoNI3XxNar9PA9sRucZx7mgzfWpFQ/exec
So basically anyone who uses it should be able to access it. I just need a way to assign that data to a local JS variable. The google sheets script is published as a web app. If I'm not mistaken there is a setting to allow anyone, even anonymous to access it.
Here is my attempt at an AJAX request:
var url = "https://script.google.com/macros/s/AKfycbzsyQNJwDvQc5SvNGEDZZOoNI3XxNar9PA9sRucZx7mgzfWpFQ/exec";
var infected_data = jQuery.ajax({
crossDomain: true,
url: url,
method: "GET",
//dataType: "jsonp"
});
If I uncomment the jsonp I get an error:
jquery-1.11.3.min.js:5 Cross-Origin Read Blocking (CORB) blocked cross-origin response https://script.googleusercontent.com/macros/echo?user_content_key=JXkCjiJjhcjndRREjoGyVNkZNkD-HvKpEPkpicQBm9nR9OkxjGXdYuOPsLxbJf-B9Rgifl5NWMtzgjfVGuMdGxTJrjKnRpdcOJmA1Yb3SEsKFZqtv3DaNYcMrmhZHmUMWojr9NvTBuBLhyHCd5hHazTNYZyoqG0ZuVXpWSNdoeLErB4AfUCNPKJHgELe5WaAmN5SlwIhonlWkkbFzR8kUwjKrMtdq9u-YqreD7W_KJ_aVqKVBTehAuogPCoZCfVc4yJf5ieDCdMDbXQ8FZZq8iSedsk1Px1LnPBLM8W-ZRcknnbJNT8dS525XG1pNEBR&lib=Mw_Scq3iKhByBS86NJpd_CngcdEShCw7K with MIME type application/json. See https://www.chromestatus.com/feature/5629709824032768 for more details.
I don't get any errors if i remove it. However, i still can't see the data on my interactive map (My application).
Using Fetch:
const url = "https://script.google.com/macros/s/AKfycbzsyQNJwDvQc5SvNGEDZZOoNI3XxNar9PA9sRucZx7mgzfWpFQ/exec";
// Declare an async function
const getData = async () => {
// Use the await keyword to let JS know this variable has some latency so it should wait for it to be filled
// When the variable is fetched, use the .then() callback to carry on
const DataJSON = await fetch(url).then(response =>
response.json()
).then(parsedResponse => parsedResponse)
return await DataJSON
};
console.log(getData());
var infected_data = getData();
Converting Integers in object to Strings
The object needs to be in a format like this:
var infected_data = {
cn: "83",
th: "0",
mo: "0",
au: "0",
sg: "0",
tw: "0",
us: "0",
jp: "0",
my: "0",
kr: "0",
fx: "0",
vn: "0",
kh: "0",
ca: "0",
ci: "0",
np: "0",
lk: "0",
};

You're likely having issues with the call being asynchronous, which would mean you're reading the data before it is actually returned from Google's servers. Try using promises and the fetch API
const url = "https://script.google.com/macros/s/AKfycbzsyQNJwDvQc5SvNGEDZZOoNI3XxNar9PA9sRucZx7mgzfWpFQ/exec";
// Declare an async function
const getData = async () => {
// Use the await keyword to let JS know this variable has some latency so it should wait for it to be filled
// When the variable is fetched, use the .then() callback to carry on
const DataJSON = await fetch(url).then(response =>
response.json()
).then(parsedResponse => parsedResponse)
return await DataJSON
};
console.log(await getData())

Assuming the data is not sensitive, You could use jsonp to bypass cors:
Server side:
return ContentService.createTextOutput("infect(" +JSON.stringify(result)+ ")").setMimeType(ContentService.MimeType.JAVASCRIPT);
Client side:
<script>function infect(data){ infectedData = data }</script>
<script src="URL_OF_YOUR_SCRIPT"></script>
References:
Jsonp
Same origin policy

Answering the Question to Convert Integers to Strings:
Try something like this:
function toString(o) {
Object.keys(o).forEach(k => {
if (typeof o[k] === 'object') {
return toString(o[k]);
}
o[k] = '' + o[k];
});
return o;
}

Related

Why do I have the error of "Undefined variable: req"?

I want to display a map of the search. But I keep getting "undefined variable: req" notification. What should I change from my following code:
var jQuery_1_8_2 = jQuery.noConflict();
$(function () {
var array = JSON.parse('{!! !empty($total_search_query) ? json_encode($total_search_query) : "[]" !!}');
console.log(array);
$('#map2').vectorMap({
map: 'indonesia-adm1_merc',
backgroundColor: '#ADF3F0',
regionStyle: {
initial: {
fill: '#FFFFFF'
},
hover: {
fill: '#175083'
}
},
zoomButtons: false,
zoomOnScroll: false,
zoomOnClick: false,
zoomMax: 1,
normalizeFunction: 'polynomial',
onRegionClick: function (event, code) {
var url = '{{ route("search", ["q" => $req->input("q"), "province" => ":id"]) }}';
url = url.replace("%3Aid", code.toLowerCase());
window.location.href = url;
},
onRegionTipShow: function (event, label, code) {
var map = $('#map2').vectorMap('get', 'mapObject');
var regionName = map.getRegionName(code);
var a = array.find(a => a.name === myTrim(regionName))['count'];
label.html('<div class="map-tooltip"><h4 class="header">' + regionName + '</h4><p class="description">Total: ' + a + '</p></div>');
}
});
}(jQuery_1_8_2));
The problem is with the $req->input("q") part that you can determine via looking at the error message which complains about $req not being defined. The reason is that in your Laravel code at some place you have stored the result of request() into a variable called $req, which does not exist in this context. This is the view part, while you have probably parsed the result of request() in your controller. As a result you will need
request()->input("q")
instead.

Bind plotly on click to vue.js data

I am creating project with vue.js and plot.ly javascript graph library.
How can I bind in "pts" to vue's data's "TestSentences"?
Here is my code ,
thank you to everyone who contributed
My goal is to create an interactive dashboard using this variable. In this way, I can change the data by clicking anywhere on the chart.
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<div id="app">
<div id="grafik"></div>
</div>
<!-- Vue-->
<script>
var app = new Vue({
el: '#app',
data: {
TestSentences: "",
},
methods: {
grafikCiz() {
var trace1 = {
x: [1, 2, 3],
y: ["book", "pencil", "bag"],
mode: 'markers',
marker: {
color: ['#6886c5', '#f40552', '#1b1b2f'],
size: [10, 20, 30]
}
};
var data = [trace1];
var layout = {
height: 400,
width: 400,
};
Plotly.newPlot('grafik', data, layout);
},
},
mounted: function () {
this.grafikCiz();
},
});
</script>
<!-- Vue -->
<script>
var my_graph = document.getElementById('grafik');
my_graph.on('plotly_click', function (data) {
for (var i = 0; i < data.points.length; i++) {
pts = 'x = ' + data.points[i].x + '\ny = ' + data.points[i].y + '\n\n';
};
alert('Closest point clicked:\n\n' + pts);
});
</script>
Use plolty wrapper for vue.js https://github.com/David-Desmaisons/vue-plotly
You can add ref to the component
<vue-plotly v-show="display" :data="graphData" :layout="calculatedLayoutSizes" id="3dPlot"
:display-mode-bar="false" ref="crazyPlotly"></vue-plotly>
then use the ref within your mount point or similar method
this.$refs.crazyPlotly.$on('click', d => {
console.log(d);
});
"d" is an obj with values like x and y datapoint, index...etc
source: https://github.com/statnett/vue-plotly/issues/23
As Alagappan A already pointed out, https://github.com/David-Desmaisons/vue-plotly can make working with plotly in javascript much easier. For me it was sufficient to just:
<vue-plotly :data="data" :layout="layout" #click="temp"> </vue-plotly>
which can directly be utilized in a method:
methods: {
temp (value) {
console.log(value)
}
}

how to send a message to direct line chat bot from the UI using JavaScript

I'm developing a chat bot (v4 using MS Azure bot framework & QnAmaker),
I've added a feature in that, i.e. while the users starts typing the questions, the bot will get prompt and show the relevant questions form the QnAmaker , and the user can select one of them , then that particular question will sent to the bot.
Following is the full code which I'm using,
<html>
<body>
<div id="webchat" role="main"></div>
<script>
(async function () {
const styleOptions = {
hideUploadButton: true,
bubbleBackground: '#D8F4FF',
bubbleFromUserBackground: '#E8E8E8',
botAvatarImage: '../botavatar.PNG',
botAvatarInitials: 'bot',
userAvatarInitials: initial,
userAvatarImage: userimg,
rootHeight: '100%',
rootWidth: '50%'
};
const styleSet = window.WebChat.createStyleSet({
bubbleBackground: 'rgba(0, 0, 255, .1)',
bubbleFromUserBackground: 'rgba(0, 255, 0, .1)'
});
styleSet.textContent = {
fontFamily: "'Comic Sans MS', 'Arial', sans-serif",
fontWeight: 'bold'
};
const secret = secret;
const res = await fetch('https://directline.botframework.com/v3/directline/tokens/generate',
{
headers: {
Authorization: `Bearer ${secret}`,
},
method: 'POST'
});
const { token } = await res.json();
const store = window.WebChat.createStore(
{},
({ dispatch }) => next => action => {
if (action.type === 'DIRECT_LINE/CONNECT_FULFILLED') {
dispatch({
type: 'WEB_CHAT/SEND_EVENT',
payload: {
name: 'webchat/join',
}
});
}
return next(action);
}
);
window.WebChat.renderWebChat({
directLine: window.WebChat.createDirectLine({ token }),
store,
styleOptions,
userID: emailid,
username: fullname,
locale: 'en-US',
userAvatarInitials: initial
}, document.getElementById('webchat'));
document.querySelector('#webchat > *').focus();
document.querySelectorAll('[aria-label="Sendbox"]')[0].placeholder = "Type your question and press enter";
$("[aria-label='Sendbox']").keypress(function () {
if ($("[aria-label='Sendbox']")[0].defaultValue.length > 4) {
getquestion(this.value);
} else {
$('#ques').remove();
}
});
$('div.probing').click(function () { alert(this.innerText); });
$('div.probing').click(function () {
document.querySelectorAll('[aria-label="Sendbox"]')[0].value = (this.innerText);
document.querySelectorAll('[aria-label="Sendbox"]')[0].defaultValue = (this.innerText);
$('.css-115fwte').trigger('click');
$('#ques').remove();
});
})().catch(err => console.error(err));
function getquestion(value) {
var token = secret;
var questionquery =
{
question: value,
top: 2,
scoreThreshold: 50,
"strictFilters": [
{
"name": "message",
"value": "text"
}],
}
$.ajax({
type: "POST",
url: "https://endpoint/qnamaker/knowledgebases/KBID/generateAnswer",
data: JSON.stringify(questionquery),
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', secret);
},
dataType: "json",
contentType: "application/json",
success: function (data) {
var questions = "";
$('#ques').remove();
for (var i = 0; i < 4; i++) {
if (data.answers[0].questions[i] != null && data.answers[0].questions[i] != 'undefined')
questions = questions + "<div class='probing'>" + data.answers[0].questions[i] + "</div>";
}
$('.content').last().append("<div id='ques'>" + questions + "</div>");
$('div.probing').click(function () {
document.querySelectorAll('[aria-label="Sendbox"]')[0].value = (this.innerText);
document.querySelectorAll('[aria-label="Sendbox"]')[0].defaultValue = (this.innerText);
$('.css-115fwte').trigger('click');
$('#ques').remove();
});
},
error: function (data) {
alert(data.responseText);
}
});
}
</script>
</body>
</html>
Please check the below image of my bot with the prompted questions, it will look like this, these questions are get appended to the last reply given by the bot, after selecting the question, this div will get removed. On the next question this cycle will continue again.
Problem I'm facing is here, with the following code the value is getting entered in the input box, however the bot does not received any question, and hence it failed to answer.
$('div.probing').click(function () {
document.querySelectorAll('[aria-label="Sendbox"]')[0].value = (this.innerText);
document.querySelectorAll('[aria-label="Sendbox"]')[0].defaultValue = (this.innerText);
$('.css-115fwte').trigger('click');
$('#ques').remove();
});
With this code the value is getting entered in the input box, however the bot does not received any question, and hence it failed to answer.
this is how it will in console after adding the question by script.
Note that I've used all the required reference JS and CSS Files in my code.
So please help me with the correct approach to achieve my requirement, Thanks in Advance.
Here's a working demo that should get you started, using a similar method from the sample:
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>Web Chat: Programmatic access to post activity</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<!--
This CDN points to the latest official release of Web Chat. If you need to test against Web Chat's latest bits, please refer to pointing to Web Chat's MyGet feed:
https://github.com/microsoft/BotFramework-WebChat#how-to-test-with-web-chats-latest-bits
-->
<script src="https://cdn.botframework.com/botframework-webchat/latest/webchat.js"></script>
<style>
html,
body {
height: 100%;
}
body {
margin: 0;
}
#webchat {
height: 100%;
width: 100%;
}
</style>
</head>
<body>
<div id="webchat" role="main"></div>
<script>
(async function () {
// In this demo, we are using Direct Line token from MockBot.
// Your client code must provide either a secret or a token to talk to your bot.
// Tokens are more secure. To learn about the differences between secrets and tokens
// and to understand the risks associated with using secrets, visit https://learn.microsoft.com/en-us/azure/bot-service/rest-api/bot-framework-rest-direct-line-3-0-authentication?view=azure-bot-service-4.0
// We are creating the Web Chat store here so we can dispatch WEB_CHAT/SEND_MESSAGE action later.
const store = window.WebChat.createStore();
window.WebChat.renderWebChat(
{
directLine: window.WebChat.createDirectLine({ token: '<your token>' }),
// We are passing our own version of Web Chat store.
store
},
document.getElementById('webchat')
);
document.querySelector('#webchat > *').focus();
// THIS IS THE IMPORTANT STUFF
const sendbox = document.querySelector("[aria-label='Sendbox']");
function removeQuestions() {
const questionDivs = document.querySelectorAll('.questions');
questionDivs.forEach((div) => {
div.remove();
})
}
// This ensures that we create unique listeners for each question
let totalQuestions = 0;
// Track the keypress events in the Send Box
sendbox.addEventListener('keypress', () => {
if (sendbox.defaultValue.length > 4) {
getQuestion();
} else {
removeQuestions();
}
});
// Send a message containing the innerText of the target element
function send(event) {
store.dispatch({
type: 'WEB_CHAT/SEND_MESSAGE',
payload: { text: event.currentTarget.innerText }
});
event.currentTarget.remove();
}
// This generates some test questions
function getQuestion() {
// Create questions div
const questions = document.createElement('DIV');
questions.setAttribute('class', 'questions');
document.querySelector('.content').appendChild(questions);
// Generate test questions
for (var i = 0; i < 4; i++) {
// Create question div
const question = document.createElement('DIV');
question.setAttribute('id', `question${totalQuestions}`);
question.setAttribute('class', 'probing');
question.innerText = `this is a test ${totalQuestions}`;
questions.appendChild(question);
// Create listener for question
const element = document.querySelector(`#question${totalQuestions}`);
element.addEventListener('click', send, false);
totalQuestions++;
}
}
})().catch(err => console.error(err));
</script>
</body>
</html>
There are likely more elegant ways to do this, but I wanted to get an answer out to you ASAP.
Note: I used vanilla javascript over jQuery to cut down on page load times and because I'm more familiar with it.

getJSON method does not work

Below is my code where getJSON method is not working
function loadJson() {
$(document).ready(function () {
alert("inside");
var chart;
var url = "values.json";
var seriesData = [];
var xCategories = [];
var i, cat;
alert("outside");
$.getJSON(url, function (data) {
alert("inside JSON function");
for (i = 0; i < data.length; i++) {
cat = '' + data[i].period_name;
if (xCategories.indexOf(cat) === -1) {
xCategories[xCategories.length] = cat;
}
}
for (i = 0; i < data.length; i++) {
if (seriesData) {
var currSeries = seriesData.filter(function (seriesObject) {
return seriesObject.name == data[i].series_name;
}
);
if (currSeries.length === 0) {
seriesData[seriesData.length] = currSeries = { name: data[i].series_name, data: [] };
} else {
currSeries = currSeries[0];
}
var index = currSeries.data.length;
currSeries.data[index] = data[i].period_final_value;
}
else {
seriesData[0] = { name: data[i].series_name, data: [data[i].period_final_value] }
}
}
//var chart;
//$(document).ready(function() {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'bar'
},
title: {
text: 'Stacked column chart'
},
xAxis: {
categories: xCategories
},
yAxis: {
//min: 0,
//max: 100,
title: {
text: 'Total fruit consumption'
},
stackLabels: {
enabled: false,
style: {
fontWeight: 'bold',
color: (Highcharts.theme && Highcharts.theme.textColor) || 'gray'
}
}
},
legend: {
align: 'right',
x: -100,
verticalAlign: 'top',
y: 20,
floating: true,
backgroundColor: (Highcharts.theme && Highcharts.theme.legendBackgroundColorSolid) || 'white',
borderColor: '#CCC',
borderWidth: 1,
shadow: false
},
tooltip: {
formatter: function () {
return '<b>' + this.x + '</b><br/>' +
this.series.name + ': ' + this.y + '<br/>'
}
},
series: seriesData
});
});
});
}
In url , values.json is my JSON file as follows
[{"series_name":"Actual","period_name":"Q1 / 2013","period_final_value":17},
{"series_name":"Actual","period_name":"Q2 / 2013","period_final_value":15},
{"series_name":"Actual","period_name":"Q3 / 2013","period_final_value":13},
{"series_name":"Actual","period_name":"Q4 / 2013","period_final_value":19},
{"series_name":"Alarm","period_name":"Q1 / 2013","period_final_value":14.103},
{"series_name":"Alarm","period_name":"Q2 / 2013","period_final_value":14.404499999999999},
{"series_name":"Alarm","period_name":"Q3 / 2013","period_final_value":14.966999999999999},
{"series_name":"Alarm","period_name":"Q4 / 2013","period_final_value":50},
{"series_name":"Target","period_name":"Q1 / 2013","period_final_value":15.67},
{"series_name":"Target","period_name":"Q2 / 2013","period_final_value":16.005},
{"series_name":"Target","period_name":"Q3 / 2013","period_final_value":16.63},
{"series_name":"Target","period_name":"Q4 / 2013","period_final_value":100}]
file renders but data is not shown on chart, only the alert outside the getJSON method works, inner one doesnot works, the same code if I try to run from html page then it works fine, but now I have written the entire code as it is in VS in ASP.NET Web Application and I have called the loadJson function on body onLoad in javascript as follows,
<body onload="loadJson();">
but the method doesn't run,
not able to solve this, any help will be greatly appreciated...
----------Additional work------
when I add my JSON data in any variable above the getJSON method and eliminate the getJSON method and access that then I get the Graph properly but when I am using getJSON method then it's not working
-----Error Inspected----------
I inspected the error in chrome and I got to know it is not able to get the json file, I have kept the JSON file in project folder , then also I tried by keeping the json file in localhost, still its saying same error..
Now I am thinking I am facing problem with mime type handling with aspx page..is it anything to link with it..??
1) Make sure you are using a valid json: www.jsonlint.com
2) Run your json file on localhost. Tell me if you see the json file on your browser run on localhost. Make sure you have this in your web.config
<system.webServer>
<staticContent>
<mimeMap fileExtension=".json" mimeType="application/json" />
</staticContent>
</system.webServer>
3) Alert info using getJSON function
$(document).ready(function () {
$.getJSON("values.json", function (data) {
$.each(data, function () {
alert(this.series_name);
});
});
});
4) When you pass these tests, continue building up your jQuery codes.
Is there any error with the call of file?
try the following:
$.getJSON(url)
.done(function(data) {
alert("INSIDE FUNCTION")
})
.fail(function(jqXHR, textStatus) {
alert("Request failed: " + textStatus);
});
I use this coding style mostly for all jquery ajax (and wrapper) calls, so that I can give the user a response if
the request failed.
Use $.getJSON not $.get like,
$.getJSON(url, function (data) {
alert("inside JSON function");
And Check your json is valid or not (Check a JSON tab is there in your console)
http://jsonlint.com/ found an issue with your JSON
[{"series_name":"Actual","period_name":"Q1 / 2013","period_final_value":17},
{"series_name":"Actual","period_name":"Q2 / 2013","period_final_value":15},
{"series_name":"Actual","period_name":"Q3 / 2013","period_final_value":13},
{"series_name":"Actual","period_name":"Q4 / 2013","period_final_value":19},]
Its not a valid JSON because of the , just before the ] bracket.

FuelUX datagrid not loading (using example)

I'm new to FuelUX so I was trying to get this to work, based on the example provided:
require(['jquery','data.js', 'datasource.js', 'fuelux/all'], function ($, sampleData, StaticDataSource) {
var dataSource = new StaticDataSource({
columns: [{property:"memberid",label:"LidId",sortable:true},{property:"name",label:"Naam",sortable:true},{property:"age",label:"Leeftijd",sortable:true}],
data: sampleData.memberdata,
delay: 250
});
$('#MyGrid').datagrid({
dataSource: dataSource,
stretchHeight: true
});
});
});
With this as the data:
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
define(factory);
} else {
root.sampleData = factory();
}
}(this, function () {
return {
"memberdata": [{
"memberid": 103,
"name": "Laurens Natzijl",
"age": "25"
}, {
"memberid": 104,
"name": "Sandra Snoek",
"age": "25"
}, {
"memberid": 105,
"name": "Jacob Kort",
"age": "25"
}, {
"memberid": 106,
"name": "Erik Blokker",
"age": "25"
}, {
"memberid": 107,
"name": "Jacco Ruigewaard",
"age":"25"
},{ /* etc */ }]
}
}));
I've got no console errors, no missing includes. Everthing works just fine - it even looks like it's loading. Except nothing shows up in the datagrid but '0 items'.
Any suggestions? I think I did everything the example provided...
EDIT: 14:33 (Amsterdam)
There seems to be a difference when I put this in console:
My page:
require(['jquery','data.js','datasource.js', 'fuelux/all'], function ($, sampleData, StaticDataSource) {
var dataSource = new StaticDataSource({
columns: [{property:"memberid",label:"LidId",sortable:true},{property:"name",label:"Naam",sortable:true},{property:"age",label:"Leeftijd",sortable:true}],
data: sampleData.memberdata,
delay: 250
});
console.debug(dataSource);
});
1st row in console:
function localRequire(deps, callback, errback) { /* etc */ }
2nd row in console:
StaticDataSource {_formatter: undefined, _columns: Array[3], _delay: 250, _data: Array[25], columns: function…}
FuelUX Example:
require(['jquery', 'sample/data', 'sample/datasource', 'sample/datasourceTree', 'fuelux/all'], function ($, sampleData, StaticDataSource, DataSourceTree) {
var dataSource = new StaticDataSource({
columns: [{property: 'toponymName',label: 'Name',sortable: true}, {property: 'countrycode',label: 'Country',sortable: true}, {property: 'population',label: 'Population',sortable: true}, {property: 'fcodeName',label: 'Type',sortable: true}],
data: sampleData.geonames,
delay: 250
});
console.debug(dataSource);
});
1st row in console:
StaticDataSource {_formatter: undefined, _columns: Array[4], _delay: 250, _data: Array[146], columns: function…}
2nd row in console:
function (deps, callback, errback, relMap) { /* etc */ }
Maybe this will help you help me :)
I didn't see all of the information I needed to provide a finite answer. The real magic is the datasource.js file (which you had not provided).
I thought an easier way of demonstrating all the necessary pieces would be to put together a JSFiddle showing your data in use and all the pieces that were necessary.
Link to JSFiddle of Fuel UX Datagrid sample with your data
Adam Alexander, the author of the tool, also has written a valuable example of using the dataGrid DailyJS Fuel UX DataGrid
// DataSource Constructor
var StaticDataSource = function( options ) {
this._columns = options.columns;
this._formatter = options.formatter;
this._data = options.data;
this._delay = options.delay;
};
StaticDataSource.prototype = {
columns: function() {
return this._columns
},
data: function( options, callback ) {
var self = this;
var data = $.extend(true, [], self._data);
// SEARCHING
if (options.search) {
data = _.filter(data, function (item) {
for (var prop in item) {
if (!item.hasOwnProperty(prop)) continue;
if (~item[prop].toString().toLowerCase().indexOf(options.search.toLowerCase())) return true;
}
return false;
});
}
var count = data.length;
// SORTING
if (options.sortProperty) {
data = _.sortBy(data, options.sortProperty);
if (options.sortDirection === 'desc') data.reverse();
}
// PAGING
var startIndex = options.pageIndex * options.pageSize;
var endIndex = startIndex + options.pageSize;
var end = (endIndex > count) ? count : endIndex;
var pages = Math.ceil(count / options.pageSize);
var page = options.pageIndex + 1;
var start = startIndex + 1;
data = data.slice(startIndex, endIndex);
if (self._formatter) self._formatter(data);
callback({ data: data, start: 0, end: 0, count: 0, pages: 0, page: 0 });
}
};
If you were to provide your markup and what your "datasource.js" file contains, I may be able to help you further.
I think the demonstration provides much information on any pieces you may not have understood.
Adding on to creatovisguru's answer:
In his JSFiddle example, pagination is broken. To fix it, change the following line:
callback({ data: data, start: start, end: end, count: count, pages: pages, page: page });
I had the exact same issue, when tried to integrate with Django. The issue I believe is on this line :
require(['jquery','data.js','datasource.js', 'fuelux/all'], function ($, sampleData, StaticDataSource) {
I was not able to specify file extension, my IDE (pycharm), would mark "red", when used "data.js", so it needs to stay without an extension, such as "sample/data"
What I end up doing to make it work, is downloading the full fuelux directory from github in /var/www/html on a plain Apache setup ( no django, to avoid URL.py issues for static files ) and everything works using their example. Here are the steps to get you started :
cd /var/www/html
git clone https://github.com/ExactTarget/fuelux.git
and you will end up with fuelux in /var/www/html/fuelux/
in your browser, navigate to : http://foo.com/fuelux/index.html ( assuming your default document root is /var/www/html )
good luck!

Categories