JSonRestStore and CLientfilter - json

I've setup a little script for testing JRS and a clientfilter. I've used what I could find on the internet to set it up but it ain't working. I'm trying to perform a client side fetch on a JRS using clientFilter. Nevertheless the JRS is querying the backend in stead of performing the fetch clientsided. I pasted the script below, I hope one of you can explain why it isn't working.
Thanks
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="js/dojo-release-1.7.2/dojo/resources/dojo.css"/>
<link rel="stylesheet" type="text/css" href="js/dojo-release-1.7.2/dijit/themes/tundra/tundra.css"/>
<script>
dojoConfig= {
has: {
"dojo-firebug": true
},
parseOnLoad: true,
isDebug: true,
locale: "nl"
};
</script>
<script type="text/javascript" src="js/dojo-release-1.7.2/dojo/dojo.js"></script>
<script type="text/javascript">
dojo.require("dojox.data.ClientFilter");
dojo.require("dojox.data.JsonRestStore");
dojo.require("dijit.form.Button");
myStore = new dojox.data.JsonRestStore({target:"TARGET"});
myStore.fetch();
dojo.ready(function() {
dojo.connect(dijit.byId("query"), "onClick", function() {
myStore.fetch({query:{id:"4"},queryOptions:{cache:true}, onItem: function(item) {console.log(item); }});
});
});
</script>
</head>
<body cllass="tundra">
<button type="button" id="query" data-dojo-type="dijit.form.Button">Query</button>
</body>

I made a jsfiddle that shows how to do this with the new syntax and dojo stores.
http://jsfiddle.net/SgyYW/
require([
"dojo/store/Cache",
"dojo/store/JsonRest",
"dojo/store/Memory",
"dojo/parser",
"dojo/on",
"dojo/ready",
"dijit/form/Button",
"dijit/registry"
],function(Cache,JsonRest,Memory,parser,on,ready,Button,registry){
console.log('x');
var someData = [
{id:1, name:"One"},
{id:2, name:"Two"},
{id:3, name:"Three"},
{id:4, name:"Four"},
{id:5, name:"Five"}
];
recToQuery = 4;
// recToQuery = 6; // try one that is not in the cache
var memoryStore = new Memory({data: someData});
var restStore = new JsonRest({ target: "/i/dont/exist.json/"});
var myStore = new Cache(restStore, memoryStore);
myStore.query({}); // this will ask for everything and prime the cache
ready(function(){
parser.parse();
var queryBtn = registry.byId("query");
console.log('queryBtn',queryBtn);
on(queryBtn, "click", function() {
console.log('query button clicked',[this,arguments]);
var resultOrPromise = myStore.get(recToQuery);
if (typeof resultOrPromise.then ==='function'){
// it is asking the server
resultOrPromise.then(function(){
console.log('Result from server fetch',arguments);
},function(){
console.log('it queried the server but failed',arguments);
});
}else{
// it is in the cache (from the first query)
console.log('result from cache:',resultOrPromise);
}
});//end connect
}); //end ready
}); //end require

Related

How to upload a File to Firebase using HTML and store user details with link in DATABASE

I have a website in which I want to add a file upload option so how to do it using firebase in HTML
and I also want to collect user details while uploading files like users entering details and storing them in the database. How to do it.
I am a beginner in programming that's why I am asking please help me who knows the answer if possible please provide the code
The code which I have tried :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div>
Upload Files<br />
<input type="file" id="files" multiple /><br /><br />
<button id="send">Upload</button>
<p id="uploading"></p>
<progress value="0" max="100" id="progress"></progress>
</div>
<!-- The core Firebase JS SDK is always required and must be listed first -->
<script src="https://www.gstatic.com/firebasejs/7.13.1/firebase-app.js"></script>
<!-- TODO: Add SDKs for Firebase products that you want to use -->
<script src="https://www.gstatic.com/firebasejs/7.13.1/firebase-storage.js"></script>
<script>
// Your web app's Firebase configuration
var firebaseConfig = {
apiKey: "******************",
authDomain: "******************",
projectId: ******************,
storageBucket: ******************,
messagingSenderId: "******************",
appId: "******************",
measurementId: "******************"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
</script>
<script>
var files = [];
document.getElementById("files").addEventListener("change", function(e) {
files = e.target.files;
for (let i = 0; i < files.length; i++) {
console.log(files[i]);
}
});
document.getElementById("send").addEventListener("click", function() {
//checks if files are selected
if (files.length != 0) {
//Loops through all the selected files
for (let i = 0; i < files.length; i++) {
//create a storage reference
var storage = firebase.storage().ref(files[i].name);
//upload file
var upload = storage.put(files[i]);
//update progress bar
upload.on(
"state_changed",
function progress(snapshot) {
var percentage =
(snapshot.bytesTransferred / snapshot.totalBytes) * 100;
document.getElementById("progress").value = percentage;
},
function error() {
alert("error uploading file");
},
function complete() {
document.getElementById(
"uploading"
).innerHTML += `${files[i].name} upoaded <br />`;
}
);
}
} else {
alert("No file chosen");
}
});
function getFileUrl(filename) {
//create a storage reference
var storage = firebase.storage().ref(filename);
//get file url
storage
.getDownloadURL()
.then(function(url) {
console.log(url);
})
.catch(function(error) {
console.log("error encountered");
});
}
</script>
</body>
</html>

how to store the JSON from directive to use it on next HTML page through angular

I have a requirement that i need to read a excel file from any location and to render the data of the excel on the next html page.
I was able to render the excel data with multiple sheets on the same page but now I need to select the file on first page and render its data on the next html page.
Like this:
And on the next screen need to show excel data:
Here in the Sheet Name i need to provide the sheet names from excel and on selecting any sheet name that sheet data need to be loaded in the grid.
I have used two divs to divide the page vertically in two columns.
I was able to achieve this functionality on a single page but now I need to divide this code in multiple pages.
This is the plunker of the work done:
http://plnkr.co/edit/xHEtxtzKrEiKDTrqlafC?p=preview
This is my js code:
angular.module('app', ['ui.grid'])
.controller('MainCtrl', ['$scope', function($scope) {
var vm = this;
vm.gridOptions = {};
vm.reset = reset;
vm.selectedSheet = '';
vm.sheetIndex = 0;
function reset() {
vm.gridOptions.data = [];
vm.gridOptions.columnDefs = [];
vm.selectedSheet = '';
vm.sheetIndex = 0;
}
vm.readSheet = function() {
var workbook = XLSX.read(vm.data, {
type: 'binary'
});
var headerNames = XLSX.utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[vm.sheetIndex]], {
header: 1
})[0];
vm.sheetNames = workbook.SheetNames;
var data = XLSX.utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[vm.sheetIndex]]);
vm.gridOptions.columnDefs = [];
headerNames.forEach(function(h) {
vm.gridOptions.columnDefs.push({
field: h
});
});
vm.gridOptions.data = data;
};
vm.onLoadData = function(data) {
vm.data = vm.data || data;
vm.readSheet();
};
vm.sheetChange = function() {
vm.sheetIndex = vm.sheetNames.indexOf(vm.selectedSheet);
vm.readSheet();
};
}])
.directive("fileread", [function() {
return {
scope: {
onLoadData: '&'
},
link: function($scope, $elm, $attrs) {
$elm.on('change', function(changeEvent) {
var reader = new FileReader();
reader.onload = function(evt) {
$scope.$apply(function() {
$scope.onLoadData({
data: evt.target.result
});
$elm.val(null);
});
};
reader.readAsBinaryString(changeEvent.target.files[0]);
});
}
}
}]);
HTML code:
<!DOCTYPE html>
<html ng-app="app">
<head>
<link data-require="bootstrap-css#*" data-semver="3.3.1" rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" />
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.16/angular.js"></script>
<script src="https://cdn.rawgit.com/SheetJS/js-xlsx/v0.8.0/dist/xlsx.full.min.js"></script>
<script src="https://cdn.rawgit.com/SheetJS/js-xlsx/v0.8.0/dist/ods.js"></script>
<script src="http://cdn.rawgit.com/angular-ui/ui-grid.info/gh-pages/release/3.0.0-rc.22/ui-grid.min.js"></script>
<link rel="stylesheet" href="http://cdn.rawgit.com/angular-ui/ui-grid.info/gh-pages/release/3.0.0-rc.22/ui-grid.min.css" />
<link rel="stylesheet" href="main.css" type="text/css" />
</head>
<body>
<div ng-controller="MainCtrl as vm">
<button type="button" class="btn btn-success" ng-click="vm.reset()">Reset Grid</button>
<br />
<br />
<div id="grid1" ui-grid="vm.gridOptions" class="grid">
<div class="grid-msg-overlay" ng-show="!vm.gridOptions.data.length">
<div class="msg">
<div class="center">
<span class="muted">Select Spreadsheet File</span>
<br />
<input type="file" accept=".xls,.xlsx,.ods" multiple="true" fileread="" on-load-data="vm.onLoadData(data)"/>
</div>
</div>
</div>
<div>
<select ng-model="vm.selectedSheet" ng-options="names as names for names in vm.sheetNames"
ng-change="vm.sheetChange()"></select>
{{vm.selectedSheet}}
</div>
</div>
</div>
<script src="app.js"></script>
</body>
</html>
I think i need to store this JSON somewhere, so that it can be used later in different pages.
Should I use service to achieve this functionality or any other approach need to be used please suggest.
I hope this might help!
You can just store the Json data in to any rootScope variable to use in another controllers.
For Example:
You have the following code;
vm.readSheet = function() {
var workbook = XLSX.read(vm.data, {
type: 'binary'
});
var headerNames = XLSX.utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[vm.sheetIndex]], {
header: 1
})[0];
vm.sheetNames = workbook.SheetNames;
var data = XLSX.utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[vm.sheetIndex]]);
vm.gridOptions.columnDefs = [];
headerNames.forEach(function(h) {
vm.gridOptions.columnDefs.push({
field: h
});
});
vm.gridOptions.data = data;
};
in here
vm.gridOptions.data = data;
you can set and store data for later usage as an JSON Array;
$rootScope.gridOptionsData = data;

Using one iron-ajax element for multiple requests

Theoretically, it should be possible to use one iron-ajax element for multiple requests by setting the auto attribute and then repeatedly setting the url property on the element. iron-ajax has a property called activeRequests, which is a read-only array, so it seems like it has supports for queueing up multiple requests simultaneously. However in practice it does not appear to work.
For example, in the JS Bin below, I retrieve a list of book IDs for books that contain the word polymer, and then use a for loop to repeatedly set the value of url.
<!doctype html>
<html>
<head>
<meta name="description" content="single iron-ajax for multiple requests">
<meta charset="utf-8">
<base href="https://polygit.org/components/">
<script href="webcomponentsjs/webcomponents-lite.min.js"></script>
<link href="polymer/polymer.html" rel="import">
<link href="iron-ajax/iron-ajax.html" rel="import">
</head>
<body>
<dom-module id="my-el">
<template>
<iron-ajax id="ajax"
url="https://www.googleapis.com/books/v1/volumes?q=polymer"
handle-as="json"
on-response="onResponse"
last-response="{{response}}" auto></iron-ajax>
</template>
<script>
Polymer({
is: 'my-el',
properties: {
response: {
type: Object,
notify: true
}
},
onResponse: function(e) {
var ajax = this.$.ajax;
var originalUrl = 'https://www.googleapis.com/books/v1/volumes?q=polymer';
var url = ajax.lastRequest.xhr.responseURL;
if (url.includes(originalUrl)) {
console.log('this is the first request');
for (var i = 0; i < ajax.lastResponse.items.length; i++) {
ajax.url = this.url(ajax.lastResponse.items[i].id);
}
} else {
console.log(ajax.lastResponse.selfLink);
}
},
url: function(id) {
return "https://www.googleapis.com/books/v1/volumes/" + id;
}
});
</script>
</dom-module>
<my-el></my-el>
</body>
</html>
It's indeed possible to use iron-ajax for multiple requests but not with auto enabled, or else you'll hit iron-ajax's debouncer. From the Polymer docs for iron-ajax:
With auto set to true, the element performs a request whenever its url, params or body properties are changed. Automatically generated requests will be debounced in the case that multiple attributes are changed sequentially.
In your question's code:
// template
<iron-ajax auto ...>
// script
onResponse: function(e) {
...
for (var i = 0; i < ajax.lastResponse.items.length; i++) {
ajax.url = this.url(ajax.lastResponse.items[i].id);
}
}
...you're presumably expecting iron-ajax to generate a new request with each URL, but the debouncer collapses the requests into one (taking only the last invocation).
Also worth noting: The response handler's event detail (i.e., e.detail) is the corresponding iron-request, which contains the AJAX response (i.e., e.detail.response). Using the event detail is preferrable because it avoids a race condition in simultaneous requests from iron-ajax, where this.$.ajax.lastResponse or this.$.ajax.lastRequest are overwritten asynchronously.
onResponse: function(e) {
var request = e.detail;
var response = request.response;
}
To reuse iron-ajax with a new URL, disable auto (which disables the debouncer) and manually call generateRequest() after updating the URL. This would allow multiple simultaneous async requests (and activeRequests would populate with more than one request).
// template
<iron-ajax ...> <!-- no 'auto' -->
// script
onResponse: function(e) {
var request = e.detail;
var response = request.response;
...
for (var i = 0; i < response.items.length; i++) {
ajax.url = this.url(response.items[i].id);
ajax.generateRequest();
}
},
ready: function() {
this.$.ajax.generateRequest(); // first request
}
Here's a modified version of your code:
<head>
<base href="https://polygit.org/polymer+1.5.0/components/">
<script src="webcomponentsjs/webcomponents-lite.min.js"></script>
<link rel="import" href="polymer/polymer.html">
<link rel="import" href="iron-ajax/iron-ajax.html">
</head>
<body>
<x-foo></x-foo>
<dom-module id="x-foo">
<template>
<!-- We're reusing this iron-ajax to fetch more data
based on the first response, and we don't want
iron-ajax's debouncer to limit our requests,
so disable 'auto' (i.e., remove the attribute
from <iron-ajax>). We'll call generateRequest()
manually instead.
-->
<iron-ajax id="ajax"
url="https://www.googleapis.com/books/v1/volumes?q=polymer"
handle-as="json"
on-response="onResponse"
on-error="onError">
</iron-ajax>
</template>
<script>
HTMLImports.whenReady(function() {
Polymer({
is: 'x-foo',
onError: function(e) {
console.warn('iron-ajax error:', e.detail.error.message, 'url:', e.detail.request.url);
},
onResponse: function(e) {
var ajax = this.$.ajax;
var originalUrl = 'https://www.googleapis.com/books/v1/volumes?q=polymer';
var url = e.detail.url;
if (url.includes(originalUrl)) {
var books = e.detail.response.items || [];
console.log('this is the first request');
for (var i = 0; i < books.length && i < 3; i++) {
ajax.url = this.url(books[i].id);
console.log('fetching:', ajax.url);
ajax.generateRequest();
}
} else {
var book = e.detail.response;
console.log('received:', e.detail.url, '"' + book.volumeInfo.title + '"');
}
},
url: function(id) {
return "https://www.googleapis.com/books/v1/volumes/" + id;
},
ready: function() {
// generate first request
this.$.ajax.generateRequest();
}
});
});
</script>
</dom-module>
</body>
https://jsbin.com/qaleda/edit?html,console
I don't know what's up with the activeRequests property, but I was able to get it to work by re-structuring my code a little. Basically, just implement a queue, and pop off an item from the queue and set url once the last request has finished.
<!doctype html>
<html>
<head>
<meta name="description" content="http://stackoverflow.com/questions/37817472">
<meta charset="utf-8">
<base href="https://polygit.org/components/">
<script href="webcomponentsjs/webcomponents-lite.min.js"></script>
<link href="polymer/polymer.html" rel="import">
<link href="iron-ajax/iron-ajax.html" rel="import">
</head>
<body>
<dom-module id="my-el">
<template>
<iron-ajax id="ajax"
url="https://www.googleapis.com/books/v1/volumes?q=polymer"
handle-as="json"
on-response="onResponse"
last-response="{{response}}" auto></iron-ajax>
</template>
<script>
Polymer({
is: 'my-el',
properties: {
response: {
type: Object,
notify: true
},
queue: {
type: Array,
notify: true,
value: function() { return []; }
}
},
onResponse: function(e) {
var ajax = this.$.ajax;
var originalUrl = 'https://www.googleapis.com/books/v1/volumes?q=polymer';
var url = ajax.lastRequest.xhr.responseURL;
if (url.includes(originalUrl)) {
console.log('this is the first request');
for (var i = 0; i < ajax.lastResponse.items.length; i++) {
this.push('queue', ajax.lastResponse.items[i].id);
}
ajax.url = this.url(this.pop('queue'));
} else {
console.log(ajax.lastResponse.selfLink);
ajax.url = this.url(this.pop('queue'));
}
},
url: function(id) {
return "https://www.googleapis.com/books/v1/volumes/" + id;
}
});
</script>
</dom-module>
<my-el></my-el>
</body>
</html>
https://jsbin.com/beyawe/edit?html,console
You can try out iron-multiple-ajax-behavior.
Let me know if this can be useful to you.

Popup window doesn't work

I am trying to create a popup window in a map. I have tree layers in my program; the first two layers are working; the third layer where I have template is defined doesn't work, though. In the console I get following errors:
Error: Unable to draw graphic (null): Unable to complete operation.
...usePost,v=h.crossOrigin):A=!!h);g=e.mixin({},g);g._ssl&&(g.url=g.url.replace(/^h...
I tried to solve this problem, by adding time between the layers. It didn't work.
Below is my code. Please let me know if I am making any mistake. Thanks!
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<!--The viewport meta tag is used to improve the presentation and behavior of the samples
on iOS devices-->
<meta name="viewport" content="initial-scale=1, maximum-scale=1,user-scalable=no">
<title> Trees Location</title>
<link rel="stylesheet" href="http://js.arcgis.com/3.11/dijit/themes/claro/claro.css">
<link rel="stylesheet" href="http://js.arcgis.com/3.11/esri/css/esri.css">
<script src="http://js.arcgis.com/3.11/"></script>
<script>
var map;
require(["esri/config", "esri/map","esri/dijit/Popup",
"dojo/dom-construct",
"esri/dijit/PopupTemplate",
"esri/layers/FeatureLayer",
"esri/symbols/SimpleMarkerSymbol",
"esri/tasks/GeometryService",
"esri/layers/ArcGISDynamicMapServiceLayer",
"esri/layers/ArcGISTiledMapServiceLayer",
"esri/Color",
"dojo/domReady!"],
function (esriConfig, Map,Popup,domConstruct, PopupTemplate, FeatureLayer,SimpleMarkerSymbol, GeometryService, ArcGISDynamicMapServiceLayer, ArcGISTiledMapServiceLayer, Color ) {
esriConfig.defaults.geometryService = new GeometryService("http://tasks.arcgisonline.com/ArcGIS/rest/services/Geometry/GeometryServer");
var popupOptions = {
markerSymbol: new SimpleMarkerSymbol("circle", 32, null,
new Color([0, 0, 0, 0.25])),
marginLeft: "20",
marginTop: "20"
};
var popup = new Popup(popupOptions, domConstruct.create("div"));
map = new Map("map", {
center: [-76.756, 40.241],
zoom: 8,
infoWindow: popup
});
var popupTemplate = new PopupTemplate({
title: "{MEMORIAL}",
fieldInfos: [
{
fieldName: "TREEDONOR",
visible: true,
label: "Type"
},
{
fieldName: "TREESPECIES",
visible: true,
label: "Type"
},
{
fieldName: "TREEVARIETY",
visible: true,
label: "Type"
}
]
});
var customBasemap = new ArcGISTiledMapServiceLayer(
"");
map.addLayer(customBasemap);
/* setTimeout(function(){
console.log("pausing a few seconds");
map.addLayer(customBasemap);
},1000); */
var treeLayer = new ArcGISDynamicMapServiceLayer(
"");
// map.addLayer(treeLayer);
setTimeout(function(){
console.log("pausing a few seconds");
map.addLayer(treeLayer);
},1000);
var featureLayer = new FeatureLayer("",
{
infoTemplate: popupTemplate,
outFields: ["TREEDONOR","TREESPECIES","TREEVARIETY", "MEMORIAL"]
});
featureLayer.setDefinitionExpression("MEMORIAL != ''");
map.addLayer(featureLayer);
});
</script>
</head>
<body class="claro">
<div align="center"><strong> Trees Listing </strong><hr>
<i><a target="_self" href="listingtrees.html">Listing</a> | <a target="_self" href="locationtrees.html">Locations </a></i>
</div>
<br>
<div id="map" >
</div>
</body>
</html>

I can't acquire JSON data AngularJS

I want to get THE MOVIE REVIEWS API by The New York Times. I tried it using AngularJS but I was not provided.Can someone help me?
var app = angular.module('movieApp', []);
app.controller('movieController',
function movieController($scope, $http) {
$scope.fetchReviews = function() {
var api = 'http://api.nytimes.com/svc/movies/v2/reviews/all.jsonp?&offset=20&order=by-opening-date&api-key=XXX MY KEY XXX&responce-format=.jsonp&callback=JSON_CALLBACK';
$http.jsonp(api).success(function(data){
$scope.results = data.results;
});
}
});
HTML
<!DOCTYPE html>
<html lang="en" ng-app="movieApp">
<head>
<meta charset="UTF-8">
<title>Movie Review</title>
<script type="text/javascript" src="js/angular.min.js"></script>
<script type="text/javascript" src="js/app.js"></script>
</head>
<body>
<div ng-controller="movieController">
<ul class="review-cards">
<li ng-repeat="item in results">
<h2>{{item.display_title}}</h2>
<p>{{item.summary_short}}</p>
</li>
</ul>
</div>
</body>
</html>
You have to handle that event to some element or just call it in your controller.
var app = angular.module('movieApp', []);
app.controller('movieController',
function movieController($scope, $http) {
// define default value
$scope.results = [];
$scope.fetchReviews = function() {
var api = 'http://api.nytimes.com/svc/movies/v2/reviews/all.jsonp?&offset=20&order=by-opening-date&api-key=XXX MY KEY XXX&responce-format=.jsonp&callback=JSON_CALLBACK';
$http.jsonp(api).success(function(data){
$scope.results = data.results;
});
}
// call that event
$scope.fetchReviews();
});
Try it.
app.controller('movieController', function ($scope, $http) {
$scope.fetchReviews = function() {
var api = 'http://api.nytimes.com/svc/movies/v2/reviews/all.jsonp?&offset=20&order=by-opening-date&api-key=XXX MY KEY XXX&responce-format=.jsonp&callback=JSON_CALLBACK';
$http.jsonp(api).success(function(data){
$scope.results = data.results;
});
}
$scope.fetchReviews();
});
check like this