How to read JSON from external domain with javascript - json

I'm new to javascript.
I have a working code that reads a JSON file locally, now the JSON moved to another domain and I can't manage to read it. I saw all the questions on JSONP but was unsuccessful to make it work.
The original code:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="./index_files/style.css">
<link rel="stylesheet" type="text/css"
</head>
<body class="UI">
<h1 id="number"></h1>
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script>
$.getJSON('data.json', function(data)
{
var views=data.mysite.today;
document.getElementById("number").innerHTML = formatNumber(views);
});
</script>
</body>
</html>
The JSON file (data.json) looks like this:
{
"mysite":
{
"today": 1000,
"week": 7000,
"month": 30000
},
"another_site":
{
"today": 100,
"week": 700,
"month": 3000
}
}
Lets say the data.json is located on: http://www.example.com/data.json
Tried this but it obviously didn't work:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="./index_files/style.css">
<link rel="stylesheet" type="text/css"
</head>
<body class="UI">
<h1 id="number"></h1>
<script type = "text/javascript">
a = function(data) {
console.log(JSON.stringify(data));
var obj=JSON.parse(data);
var views =obj.mysite.today;
document.getElementById("number").innerHTML = formatNumber(views);
};
</script>
<script type = "text/javascript" src = "http://www.example.com/data.json"></script>
</body>
</html>
Thanks in advance.

With jQuery you can use JSONP like so to get stuff off remote servers..
$.ajax({
url: "full url to remote page goes here",
dataType: "jsonp",
success: function( response ) {
console.log( response ); // server response
}
});

Tried this from what I understood from your example:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="./index_files/style.css">
<link rel="stylesheet" type="text/css"
</head>
<body class="UI">
<h1 id="number"></h1>
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script>
$.ajax({
url: "http://www.example.com/data.json",
dataType: "jsonp",
success: function( response ) {
var views=response.today;
document.getElementById("number").innerHTML = formatNumber(views);
console.log( response ); // server response
}
});
</script>
</body>
</html>
Nothing appears on screen, error on console is:
Uncaught SyntaxError: Unexpected token :

Related

IPFS in browser: testing a simple file fetch

I want to download this file and print its contents to the console using an in-browser IPFS node. The following html file should do the job:
<!doctype html>
<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>
</title>
</head>
<body>
<script type='text/javascript' src='https://unpkg.com/ipfs#0.55.1/dist/index.min.js'></script>
<script type="text/javascript">
var ifile = 'Qmc3zqKcwzbbvw3MQm3hXdg8BQoFjGdZiGdAfXAyAGGdLi';
(async () => {
const inode = await Ipfs.create({
config: {
Addresses: {
Swarm: [
// These webrtc-star servers are for testing only
'/dns4/wrtc-star1.par.dwebops.pub/tcp/443/wss/p2p-webrtc-star',
'/dns4/wrtc-star2.sjc.dwebops.pub/tcp/443/wss/p2p-webrtc-star'
]
},
Bootstrap: []
}
})
window.inode = inode; //For poking
for await (const chunk of inode.cat(ifile)) {
console.log(chunk.toString());
}
})();
</script>
Testing IPFS file fetch
</body></html>
But it doesn't print anything. What am I missing?
You don't have any bootstrap nodes, so it can't find the CID. If you add my node for example, it works fine:
<!doctype html>
<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>
</title>
</head>
<body>
<script type='text/javascript' src='https://unpkg.com/ipfs#0.55.1/dist/index.min.js'></script>
<script type="text/javascript">
var ifile = 'Qmc3zqKcwzbbvw3MQm3hXdg8BQoFjGdZiGdAfXAyAGGdLi';
(async () => {
const inode = await Ipfs.create({
config: {
Addresses: {
Swarm: [
// These webrtc-star servers are for testing only
'/dns4/wrtc-star1.par.dwebops.pub/tcp/443/wss/p2p-webrtc-star',
'/dns4/wrtc-star2.sjc.dwebops.pub/tcp/443/wss/p2p-webrtc-star'
]
},
Bootstrap: []
}
})
window.inode = inode; //For poking
await inode.swarm.connect("/dns6/ipfs.thedisco.zone/tcp/4430/wss/p2p/12D3KooWChhhfGdB9GJy1GbhghAAKCUR99oCymMEVS4eUcEy67nt");
for await (const chunk of inode.cat(ifile)) {
console.log(chunk.toString());
}
})();
</script>
Testing IPFS file fetch
</body></html>

Angular-FusionCharts : How to fetching data from external .json file?

ar app = angular.module('chartApp', ['ng-fusioncharts']);
app.controller("MyController2", function($scope, $http){
$http.get('js/data.json').then(function(res,status,xhr){
$scope.countries = res.data;
});
});
I want to use the above JSON as the chart data.
$scope.dataSource = {
"chart": {
"caption": "Column Chart Built in Angular!",
"captionFontSize": "30",
"captionPadding": "25",
........
},
"data": [
]
How can I use the "countries" JSON to be the data for the chart above?
Many examples just declare the JSON inside the "data:[]", is there anywhere to use an external .json file?
Hey we can do something like the following:
angular.module('plunker', ['ng-fusioncharts'])
.controller('MainCtrl', ['$scope', '$http', function($scope, $http) {
const chartProps = {
"caption": "Monthly",
"xaxisname": "Month",
"yaxisname": "Revenue",
"numberprefix": "$",
"theme": "fint"
};
const getDataSource = (data = [], chart = chartProps) => {
return {
chart,
data
}
};
$http.get('./data.json')
.then(({
data
}) => $scope.dataSource = getDataSource(data));
$scope.dataSource = getDataSource();
}]);
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>
document.write('<base href="' + document.location + '" />');
</script>
<script data-require="angular.js#1.5.x" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js" data-semver="1.5.11"></script>
<script src='https://static.fusioncharts.com/code/latest/fusioncharts.js'></script>
<script src='https://static.fusioncharts.com/code/latest/themes/fusioncharts.theme.fint.js'></script>
<script src='https://fusioncharts.github.io/angular-fusioncharts/demos/js/angular-fusioncharts.min.js'></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<fusioncharts id="mychartcontainer" chartid="mychart" width="600" height="400" type="column2d" dataSource="{{dataSource}}"></fusioncharts>
</body>
</html>
Check the plunker link for a live demo.
If you see the app.js, I have a commented part below - which is 'NOT-WORKING' related implementation.
I shall be looking to it in more detail. It seems the issue is $observe is not watching deeply for changes in Object structure. So the stuff works only when we update the reference. So untill then, please follow the above step.
Thanks and lemme know in case of any concern!

Error: Could not read config from meta tag in EmberCLI

I'm getting the following error on my EmberCLI app: Could not read config from meta tag with name "my-app-name/config/environment"
I read that it has to do with having the correct content-for handlebars in app/index.html but I have all of them there:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>My app name</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
{{content-for "head"}}
<link rel="stylesheet" href="assets/vendor.css">
<link rel="stylesheet" href="assets/my-app-name.css">
{{content-for "head-footer"}}
</head>
<body>
{{content-for "body"}}
<script src="assets/vendor.js"></script>
<script src="assets/my-app-name.js"></script>
{{content-for "body-footer"}}
</body>
</html>
My config/environment.js file is:
/* jshint node: true */
module.exports = function(environment) {
var ENV = {
modulePrefix: 'my-app-name',
environment: environment,
contentSecurityPolicy: { 'connect-src': "'self' https://auth.firebase.com wss://*.firebaseio.com" },
firebase: 'https://my-app-name.firebaseio.com/',
baseURL: '/',
locationType: 'auto',
EmberENV: {
FEATURES: {
// Here you can enable experimental features on an ember canary build
// e.g. 'with-controller': true
}
},
APP: {
// Here you can pass flags/options to your application instance
// when it is created
}
};
if (environment === 'development') {
// ENV.APP.LOG_RESOLVER = true;
// ENV.APP.LOG_ACTIVE_GENERATION = true;
// ENV.APP.LOG_TRANSITIONS = true;
// ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
// ENV.APP.LOG_VIEW_LOOKUPS = true;
}
if (environment === 'test') {
// Testem prefers this...
ENV.baseURL = '/';
ENV.locationType = 'none';
// keep test console output quieter
ENV.APP.LOG_ACTIVE_GENERATION = false;
ENV.APP.LOG_VIEW_LOOKUPS = false;
ENV.APP.rootElement = '#ember-testing';
}
if (environment === 'production') {
}
return ENV;
};
Am I missing a meta tag?
Is this also the reason my browser only displays when I deploy the app through firebase:
{{content-for "head"}} {{content-for "head-footer"}} {{content-for "body"}} {{content-for "body-footer"}}
Thanks!
Ember by default stores config data in a meta tag. In my app, we opted out of storing in the meta tag, I think due to neededing to support IE8.
You can quickly fix this in your ember-cli-build.js or brocfile.js adding this line:
module.exports = function(defaults) {
var app = new EmberApp({
//...
});
app.options.storeConfigInMeta = false;
});
You can read more here:
https://github.com/ember-cli/ember-cli/pull/2298

Load json data into the factory file

I am new to AngularJS and just started learning it. How can I load the JSON file into the script.js file without directly adding the entire data.
Here is the code of the program:
<!DOCTYPE html>
<html ng-app="quizApp">
<head>
<meta charset="utf-8" />
<title>QuizApp</title>
<link rel="stylesheet" href="style.css" />
<script src="http://code.jquery.com/jquery-2.0.3.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<div class="container">
<h1 class="title">QuizApp</h1>
<quiz/>
</div>
</body>
Plunkr.
You need to correct the json pasted in ques.json (by using quotes "") otherwise if you will invoke $http.get() then you will get exception due to invalid json.
Once you will correct the json content in ques.json then just use $http and assign the result to questions variable.
E.g.
app.factory('quizFactory', function($http) {
var questions = [];
$http.get('ques.json').success(function(data) {
questions = data;
})
return {
getQuestion: function(id) {
if(id < questions.length) {
return questions[id];
} else {
return false;
}
}
};
});
Here is the demo
$http.get('ques.json')
.then(function(result){
$scope.questions = result.data;
});

How do I get the the google chrome chrome.windows.create extension function to work

I need some help with the chrome.windows.create function in javascript I just cant seem to work it out
Heres the html file:
<html>
<head>
<script>
function load() {
chrome.windows.create({ url: 'http://www.google.com', type: 'panel' });
}
</script>
</head>
<body onLoad="load()">
</body>
inline javascript codes are not allowed (by default) in chrome extensions. so you have to change the code like this.
<html>
<head>
</head>
<body>
</body>
<script src="loader.js"></script>
loader.js:
function load() {
chrome.windows.create({ url: 'http://www.google.com', type: 'panel' });
}
document.getElementsByTagName( 'body' )[0].onload = function() { load(); };
For more information about content-security policies visit: Content Security Policy (CSP) - Google Chrome