itemfilereadstore reading from json file - javascript

i'm starting out with Dojo and trying to get a thumbnail gallery to display from a json file with no luck so far. I've searched and viewed other examples but none have helped me. Please help me to see what i'm doing wrong.
It's working when specifying the data in the script however(as shown by the commented out code) I can't get it to read data from an external file.
My code so far:
<script>
require(["dojo/ready",
"dijit/registry",
"dojo/dom",
"dojo/on",
"dojo/parser",
"dojo/data/ItemFileReadStore",
"dojox/image/Gallery"
], function (ready, registry, dom, on, parser, ifrs, Gallery) {
ready(function () {
// Define the attribute names used to access the items in the data store
parser.parse();
var itemNameMap = {
imageThumbAttr: "thumb",
imageLargeAttr: "large"
};
// Define the request, with no query, and a count of 20, so 20 items will be
// requested with each request
var request = {
query: {},
count: 20
};
// var store = new ifrs(imgs);
/* imageItemStore.data = {
identifier: 'title',
label: 'Images',
items: [
{
thumb: "http://www.flickr.com/photos/44153025#N00/748348847",
large: "http://www.flickr.com/photos/44153025#N00/748348847",
title: "Photo"
}
]
};*/
imageItemStore = new dojo.data.ItemFileReadStore({ url: "/images.json" });
registry.byId('gallery1').setDataStore(imageItemStore, request, itemNameMap);
});
});
</script>
My json file:
{ items: [
{
"thumb":"images/extraWide.jpg",
"large":"images/extraWide.jpg",
"title":"I'm wide, me",
"link":"http://www.flickr.com/photos/44153025#N00/748348847"
},
{
"thumb":"images/imageHoriz.jpg",
"large":"images/imageHoriz.jpg",
"title":"I'm a horizontal picture",
"link":"http://www.flickr.com/photos/44153025#N00/735656038"
},
{
"thumb":"images/imageHoriz2.jpg",
"large":"images/imageHoriz2.jpg",
"title":"I'm another horizontal picture",
"link":"http://www.flickr.com/photos/44153025#N00/714540483"
},
{
"thumb":"images/imageVert.jpg",
"large":"images/imageVert.jpg",
"title":"I'm a vertical picture",
"link":"http://www.flickr.com/photos/44153025#N00/715392758"
},
{
"large":"images/square.jpg",
"thumb":"images/square.jpg",
"link" :"images/square.jpg",
"title":"1:1 aspect ratio"
}
]}
My markup:
<div class="claro" style="height:400px">
<div data-dojo-type="dojox.image.Gallery" id="gallery1" style="height:400px"></div>
<div data-dojo-id="imageItemStore" data-dojo-type="dojo.data.ItemFileReadStore"></div>
</div>
Any help would be greatly appreciated

Have you looked a the JsonRest store instead of an ItemFileReadStore? http://dojotoolkit.org/reference-guide/1.9/dojo/store/JsonRest.html

Related

Making table elements (from JSON) linkable

I have a JSON file that contains document titles and a URL for each. So far I've been able to render each document into a table created with DataTables. I also rendered each url into the first table row as a test. It was good that they appeared but it's not what I'm going for.
How can I make it so that each document title is linked with its respective URL? I didn't see any info. about it in the DataTables manual or its forum so I thought I'd ask.
If you'd like to see a snippet of the JSON file, please let me know.
JS snippet:
import $ from 'jquery';
import JSONfile from '../../../public/JSONfile.json';
import { basename } from 'path';
import dt from 'datatables.net';
var tableRes = '';
export default class {
constructor() {
this.loadTableData();
}
loadTableData() {
$.noConflict();
let tableRes = JSONfile.d.results.filter(function(val) {
return (val.FileLeafRef.trim().length > 0);
}).map(function(obj) {
return {
// "FileName": obj.FileLeafRef,
// "Path": obj.EncodedAbsUrl, ///// these are the URLs for each document
"Titles": obj.File.Name
}
});
$('#km-table-id').DataTable( {
columns: [
{ "data": " " },
{ "data": "Titles" }, ///// Ideally I want each Title to be linked in the table---i.e. the document names appearing blue
{ "data": " " }
],
data: tableRes,
"pagingType": "full_numbers"
});
} // ------- loadTableData
} // ------- export default class
Update: Thanks to a user on the DataTables forum, I was able to find a solution. Simply put, I had to use columDefs that was detailed under the columns.render section of the docs :
Code snippet:
return {
"Path": obj.EncodedAbsUrl,
"Titles": obj.File.Name
}
});
$('#km-table-id').DataTable( {
columns: [
{ data: "Path" }, // populates rows with each document link
{ data: "Titles" }, // populates rows with docs
{ data: "check" }
],
columnDefs: [ {
targets: 0,
data: "Path",
render: function(data) {
return 'Download';
}
}],
...
Hyperlinking actual document cells:
columnDefs: [
{
data: "Path",
render: function(data, type, row) {
return $('<a>')
.attr({target: "_blank", href: row.Path})
.text(data)
.wrap('<div></div>')
.parent()
.html();
},
targets: [] // Column position
},
...

jqGrid custom editfunc doesn't work when custom search parameters are specified

Version jqGrid used here:
#license Guriddo jqGrid JS - v5.2.0 - 2016-11-27 Copyright(c) 2008, Tony Tomov, tony#trirand.com
The first block of code below is an entire self contained implementation of jqGrid. It is in fact mostly taken from one of the examples on the jqGrid site. In it I added a snippet, the part between the comment lines with the clip markings.
That added snipped adds a custom editfunc. It works nicely (in the example it is of course more or less a stub, only doing an alert). Also, searching works, with all of its default parameters. For both, select a row and click on the respective icon of Edit or Search.
<!DOCTYPE html>
<html lang="en">
<head>
<!-- The jQuery library is a prerequisite for all jqSuite products -->
<script type="text/ecmascript" src="./lib/jquery/jquery.min.js"></script>
<!-- This is the Javascript file of jqGrid -->
<script type="text/ecmascript" src="./lib/jqGrid-js-free/js/jquery.jqGrid.js"></script>
<!-- This is the localization file of the grid controlling messages, labels, etc.-->
<!-- We support more than 40 localizations -->
<script type="text/ecmascript" src="./lib/jqGrid-js-free/js/i18n/grid.locale-en.js"></script>
<!-- A link to a jQuery UI ThemeRoller theme, more than 22 built-in and many more custom -->
<link rel="stylesheet" type="text/css" media="screen" href="./lib/jquery-ui/jquery-ui.css" />
<!-- The link to the CSS that the grid needs -->
<link rel="stylesheet" type="text/css" media="screen" href="./lib/jqGrid-js-free/css/ui.jqgrid.css" />
<meta charset="utf-8" />
<title>jqGrid without PHP - Loading Data - JSON Live</title>
</head>
<body>
<table id="jqGrid"></table>
<div id="jqGridPager"></div>
<script type="text/javascript">
$(document).ready(function () {
$("#jqGrid").jqGrid({
colModel: [
{
label: 'Title',
name: 'Title',
width: 150,
formatter: formatTitle
},
{
label: 'Link',
name: 'Link',
width: 80,
formatter: formatLink
},
{
label: 'View Count',
name: 'ViewCount',
width: 35,
sorttype:'integer',
formatter: 'number',
align: 'right'
},
{
label: 'Answer Count',
name: 'AnswerCount',
width: 25
}
],
viewrecords: true, // show the current page, data rang and total records on the toolbar
width: 780,
height: 200,
rowNum: 15,
datatype: 'local',
pager: "#jqGridPager",
caption: "Load live data from stackoverflow"
});
fetchGridData();
function fetchGridData() {
var gridArrayData = [];
// show loading message
$("#jqGrid")[0].grid.beginReq();
$.ajax({
url: "http://api.stackexchange.com/2.2/questions?order=desc&sort=activity&tagged=jqgrid&site=stackoverflow",
success: function (result) {
for (var i = 0; i < result.items.length; i++) {
var item = result.items[i];
gridArrayData.push({
Title: item.title,
Link: item.link,
CreationDate: item.creation_date,
ViewCount: item.view_count,
AnswerCount: item.answer_count
});
}
// set the new data
$("#jqGrid").jqGrid('setGridParam', { data: gridArrayData});
// hide the show message
$("#jqGrid")[0].grid.endReq();
// refresh the grid
$("#jqGrid").trigger('reloadGrid');
}
});
}
function formatTitle(cellValue, options, rowObject) {
return cellValue.substring(0, 50) + "...";
};
function formatLink(cellValue, options, rowObject) {
return "<a href='" + cellValue + "'>" + cellValue.substring(0, 25) + "..." + "</a>";
};
/*---- 8< ------*/
// editfunc here works (an alert is popped up), although the format of the function parameters is not according to spec:
// searchfunc also works (it is the default)
$('#jqGrid').jqGrid( 'navGrid', '#jqGridPager',{
add:false, del:false, view:false,
editfunc: function(){alert('EDIT');}
});
/*---- >8 ------*/
});
</script>
</body>
</html>
Now take the same file, remove the small snippet between the snip lines, and replace it with the following snippet, that looks more like something I need to implement:
/*---- 8< ------*/
// editfunc does NOT work as desired here (no alert)
// search function works, WITH the parameters as specified here
// from the file jquery.jqGrid.js (): navGrid : function parameters: (elem, p, pEdit, pAdd, pDel, pSearch, pView)
// (=jqGrid-free #license Guriddo jqGrid JS - v5.2.0 - 2016-11-27 Copyright(c) 2008, Tony Tomov, tony#trirand.com)
$('#jqGrid').jqGrid( 'navGrid', '#jqGridPager',
{ add:false, del:false, view:false }, // p
{ editfunc: function(r){alert('EDIT');} }, // pEdit (does NOT work)
{ }, // pAdd
{ }, // pDel
{ multipleSearch: true, closeAfterSearch:true, closeOnEscape:true, searchOnEnter:true, showQuery:true }, // pSearch (works with these options)
{ } // pView
);
/*---- >8 ------*/
Here, alas the editfunc does not work at all, I get the default edit function. Search now works though, as desired with the custom specified parameters.
In short: I cannot seem to get both a customized editfunc and search with custom parameters working!
I cannot see anything wrong with the second snippet. It is btw. also per some examples on the jqGrid wiki.
Any hints to get both working together would be appreciated.
The problem is very easy: you placed editfunc in the wrong place in your last snippet. The editfunc should be specified as the property of the second parameter of navGrid (together with add:false, del:false, view:false). You used the editfunc correctly in the first part of your code, but you placed it in the second part of the code on the wrong place. You can fix your code by usage
$('#jqGrid').jqGrid( 'navGrid', '#jqGridPager',
{ add:false, del:false, view:false, editfunc: function(r){alert('EDIT');} }, // p
{ }, // pEdit
{ }, // pAdd
{ }, // pDel
{ multipleSearch: true, closeAfterSearch:true, closeOnEscape:true,
searchOnEnter:true, showQuery:true }, // pSearch (works with these options)
{ } // pView
);
By the way, you placed the code of commercial product Guriddo jqGrid JS in the directory jqGrid-js-free, which sounds strange. Guriddo jqGrid JS can't be used for free. You can see the current prices here. I started development of free jqGrid fork of jqGrid, which can be used completely free of charge, exactly because of that. Free jqGrid implemented many new features, which can be helpful for you. The demo https://jsfiddle.net/OlegKi/odvxefra/3/ is a small modification of your code, which displays
I used additionally
url: "https://api.stackexchange.com/2.2/questions",
// add sending of custom parameters to the URL
postData: {
order: "desc",
sort: "activity",
tagged: "jqgrid",
site: "stackoverflow"
},
datatype: "json",
// below prmNames remove sending all standard jqGrid paranmeters
prmNames: {
page: null,
rows: null,
sort: null,
order: null,
search: null,
nd: null,
id: "question_id"
},
jsonReader: {
root: "items",
repeatitems: false,
id: "question_id"
},
loadonce: true,
forceClientSorting: true,
sortname: "creation_date",
sortorder: "desc"
The data will be loaded from the same URL "http://api.stackexchange.com/2.2/questions?order=desc&sort=activity&tagged=jqgrid&site=stackoverflow", sorted locally by creation_date property in the desc order and displayed in the grid. One can use other properties in the custom formatter by adding the properties in additionalProperties. For example you can add additionalProperties: ["owner", "is_answered", "score", "last_activity_date"] to save the properties locally and to have access to the properties inside of, for example, custom formatter.

Plotly hover text not displaying

Although I've specified text and hoverinfo, I'm not getting any hover annotation at all.
If I comment out the "text" attribute, I get the default behavior of hoverinfo: "x+y". I've also tried hoverinfo: "text" and hoverinfo: "x+text" (which is what I really want), but these do not change the behavior.
https://jsfiddle.net/abalter/0cjprqgy/
var data =
{
"x":["2014-02-10 00:00:00.0","2014-02-18 00:00:00.0","2014-02-24 00:00:00.0"],
"y":[0,0,0],
"text":["gemcitabine","gemcitabine + Abraxane","Xeloda"],
"hoverinfo": "all",
"name":"Treatment",
"type":"scatter",
"mode":"markers",
"marker":
{
"size":9,
"color":"#800000"
},
"uid":"c2e171"
};
var layout =
{
"title":"Treatments",
"height":600,
"width":655,
"autosize":true,
"yaxis":
{
"titlefont":
{
"size":12,
"color":"#800000"
},
"domain":[0.85,0.9],
"showgrid":false,
"showline":false,
"showticklabels":false,
"zeroline":true,
"type":"linear",
"range":[0,0],
"autorange":true
},
"hovermode":"closest",
"xaxis":
{
"type":"date",
"range":[1389215256994.8186,1434909143005.1814],
"autorange":true
}
};
Plotly.plot('graph', [data], layout);
First of all, thank you for having me to discover this really cool graphic platform! I checked at the documentation to get to know how the data has to be formatted (here: https://plot.ly/javascript/hover-events/#coupled-hover-events-on-single-plot)... And "played" with you fiddle.
First, I removed all the unnessessary double quotes you had there, wrapping the param names and placed your value arrays outside of the "data" array. I don't know if it is part of the problem... I just tryed to format it as the example I found.
The "x+y+text" suddenly appeared when I played with the "domain" parameter.
I don't know what it really defines.
I repeat, I have a 10 minutes experience with this thing. (lol)
Check this update I made of your fiddle : https://jsfiddle.net/0cjprqgy/6/
var dates = ["2014-02-10 00:00:00.0","2014-02-18 00:00:00.0","2014-02-24 00:00:00.0"],
qty = ["0.2","0.5","1"],
product = ["gemcitabine","gemcitabine + Abraxane","Xeloda"],
data =
{
x:dates,
y:qty,
text:product,
hoverinfo: "x+y+text",
name:"Treatment",
type:"scatter",
mode:"markers",
marker:
{
size:9,
color:"#800000"
},
uid:"c2e171"
};
var layout =
{
title:"Treatments",
height:600,
width:655,
autosize:true,
yaxis:
{
titlefont:
{
size:12,
color:"#800000"
},
domain:[0.85,1.9],
showgrid:false,
showline:false,
showticklabels:false,
zeroline:true,
type:"linear",
range:[0,0],
autorange:true
},
hovermode:"closest",
xaxis:
{
type:"date",
range:[1389215256994.8186,1434909143005.1814],
autorange:true
}
};
Plotly.plot('graph', [data], layout);

Kendo UI: One data source, two widgets

UPDATE: Here is a link to reproduce the problem
RELATED: This is another question of mine where similar problems are happening with Kendo UI Map, maybe it could help someone figure this one out! It has one failing and one working version.
I use Kendo UI's DataSource, DropDownList and Map in an Angular single-page application.
I want to use the same DataSource object for both the DropDownList and the Map. However, the Map behaves in a very unpredictable manner.
When I put the DropDownList before the Map in the template, only the DropDownList gets populated. Inspecting the network traffic reveals that indeed only one request is being made. When I put the Map first, both of them get populated and two requests are made.
When I don't use any promises in transport.read, but just call options.success immediately with a static value, everything works as expected. Two calls are being made.
I've been pulling my hair over this the entire work day, so any help is highly appreciated.
The data source service:
m.factory('ourDataSource', function(foo, bar, baz) {
return new kendo.data.DataSource({
transport: {
read: function(options) {
foo().then(function (result) {
return bar(result);
}).then(function (result) {
return baz(result);
}).then(function (result) {
options.success(result);
}).catch(function (err) {
options.error(err);
});
}
}
});
});
The controller:
m.controller('ourController', ['ourDataSource', function(ourDataSource) {
// set the data source of the dropdownlist
this.ourDataSource = ourDataSource;
// set up the map layers
this.mapLayers = [{
type: 'tile',
urlTemplate: 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer/tile/#= zoom #/#= y #/#= x #',
}, {
type: 'marker',
dataSource: ourDataSource, // the same data source as before
locationField: 'Position',
titleField: 'Title'
}];
}]);
The view:
<div ng-controller="ourController as ctrl">
<select kendo-drop-down-list
k-data-text-field="'Title'"
k-data-value-field="'Title'"
k-data-source="ctrl.ourDataSource"></select>
<div kendo-map
k-zoom="2"
k-center="[1, 1]"
k-layers="ctrl.mapLayers">
</div>
</div>
What am I missing here?
I believe that this might be a bug in the Kendo UI Map widget, since the behavior occurring here isn't at all what one would expect. However, I do have a workaround solution. Rather than return the data source as a singleton object, return it as a function. This is probably not ideal, but it works.
angular.module('ourModule', ['kendo.directives'])
.factory('getDataSource', function ($q) {
return function() { // return a function that creates a new data source
return new kendo.data.DataSource({
transport: {
read: function (options) {
$q.when([
{Position: [1, 1], Title: 'First place'},
{Position: [10, 10], Title: 'Second place'}
]).then(function (result) {
options.success(result);
});
}
}
});
};
})
.controller('ourController', function (getDataSource) {
this.ourDataSource = getDataSource();
this.mapLayers = [{
type: 'tile',
urlTemplate: '...removed for brevity...'
}, {
type: 'marker',
dataSource: getDataSource(),
locationField: 'Position',
titleField: 'Title'
}];
});
Factory mostly used to create instances on demand. See this example
var app = angular.module('ourModule', ['kendo.directives']);
app.factory('dataSourceFactory', function($q) {
function dataSourceFactory() {}
dataSourceFactory.prototype = {
contentTypes: function() {
return new kendo.data.DataSource({
transport: {
read: function(options) {
$q.when(
[{
Position: [1, 1],
Title: 'First place'
}, {
Position: [10, 10],
Title: 'Second place'
}])
.then(function(result) {
options.success(result);
});
}
}
})
}
};
return dataSourceFactory;
});
app.controller('ourController', ['$scope', 'dataSourceFactory',
function($scope, dataSourceFactory) {
var dataSourceFactory = new dataSourceFactory();
$scope.mapLayers = [{
type: 'tile',
urlTemplate: 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer/tile/#= zoom #/#= y #/#= x #',
}, {
type: 'marker',
dataSource: dataSourceFactory.contentTypes(), // the same data source as before
locationField: 'Position',
titleField: 'Title'
}];
$scope.ourDataSource = dataSourceFactory.contentTypes();
}
]);
<link rel="stylesheet" href="http://kendo.cdn.telerik.com/2015.3.930/styles/kendo.common.min.css">
<link rel="stylesheet" href="http://kendo.cdn.telerik.com/2015.3.930/styles/kendo.rtl.min.css">
<link rel="stylesheet" href="http://kendo.cdn.telerik.com/2015.3.930/styles/kendo.default.min.css">
<link rel="stylesheet" href="http://kendo.cdn.telerik.com/2015.3.930/styles/kendo.mobile.all.min.css">
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://kendo.cdn.telerik.com/2015.3.930/js/angular.min.js"></script>
<script src="http://kendo.cdn.telerik.com/2015.3.930/js/jszip.min.js"></script>
<script src="http://kendo.cdn.telerik.com/2015.3.930/js/kendo.all.min.js"></script>
<div ng-app="ourModule">
<div ng-controller="ourController">
<kendo-drop-down-list k-data-source="ourDataSource"
k-data-text-field="'Title'"
k-data-value-field="'Title'">
</kendo-drop-down-list>
<kendo-map k-zoom="2"
k-layers="mapLayers">
</kendo-map>
</div>
</div>
See this JSFiddle demo

Unable to parse json data and keep it in grid using dojo

I got the json object data from servlet as this:
{"persondetails":[{"salary":"20000","sname":"XXX","sno":"1"},
{"salary":"50000","sname":"yyy","sno":"2"},
{"salary":"20300","sname":"bbb","sno":"3"},
{"salary":"20100","sname":"chan","sno":"4"},
{"salary":"40100","sname":"lorn","sno":"5"},
{"salary":"10100","sname":"san","sno":"6"},
{"salary":"60100","sname":"sun","sno":"7"},
{"salary":"20200","sname":"chan","sno":"8"},
{"salary":"10200","sname":"san","sno":"9"},
{"salary":"40200","sname":"lorn","sno":"10"}]}
Now, I have to put this in datagrid using dojo. I tried but I'm getting a blank page. Please check this and help me understand what I did wrong.
Here's my code:
var grid, dataStore, store;
require([ "dojox/grid/DataGrid", "dojo/store/Memory",
"dojo/data/ObjectStore", "dojo/request/xhr", "dojo/dom",
"dojo/dom-construct", "dojo/json", "dojo/on", "dojo/domReady!" ],
function(DataGrid, Memory, ObjectStore,xhr, dom, domConst, JSON, on) {
xhr("myserveraddress:7080/GridExample/login", {
handleAs : "json"
}).then(
function(data) {
domConst.place("<p>response: <code>"
+ JSON.stringify(data) + "</code></p>",
"output");
store = new Memory({
data : data.items
});
dataStore = new ObjectStore({
objectStore : store
});
grid = new DataGrid({
store : dataStore,
query : {
id : "*"
},
structure : [ {
name : "SNO",
field : "sno",
width : "100px"
},{
name : "SNAME",
field : "sname",
width : "100px"
},{
name : "SALARY",
field : "salary",
width : "200px"
} ]
}, "grid");
grid.placeAt("myGrid");
grid.startup();
}, function(err) {
alert("error");
}, function(evt) {
});
});
You need to give the grid the array inside persondetails.
So your store should be something like::
data.items.persondetails
Also in your grid you dont need the query parameter, unless you want a certain row like
sno:"9"
will only show rows with sno = 9
fiddle::http://jsfiddle.net/theinnkeeper/57pZf/

Categories

Resources