JQuery return variable from JSON request - json

I have the following code to pull some data from an external source:
$(document).ready(function(){
$.getJSON('mydata.json',function(data) {
var ned = data.names.ned;
return(ned);
});
});
And In my JSON I have:
{
"names": {
"ned": "Eddard Stark",
"jon": "Jon Snow",
"tyrion": "Tyrion Lannister"
}
}
I want to know how can I use the variable 'ned' on another function. Also, I want further to set other variables like 'jon' and 'tyrion' to be able to use later, but I can't make them pass to another function.
The JSON callback must be done on page load to be able to proper use some of the app functions, that's why it's on document ready.

You can do that easily using jquery $.Deferred:
function getNed()
{
return $.getJSON('mydata.json').pipe(function(data) {
var ned = data.names.ned;
return ned;
});
}
getNed().done(function(ned) {
alert(ned);
});

A quick/easy way to do this would be to declare a global variable, then fill it with your data from the json call when you get it.
<script>
var myJsonData; //Make this a very unique name, as you may conflict with other variables in plugins and such.
$(document).ready(function(){
$.getJSON('mydata.json',function(data) {
myJsonData = data;
var ned = data.names.ned;
return(ned);
});
});
</script>
However, note that your getJSON call could take a long time, and you have to be diligent in checking that the myJsonData variable is not undefined before using it. Alternatively, you could call some sort of initialization function from the json callback.

Related

How can we Read a local Json file in a html page without any server

I want to read a local Json file from a html page. But I am not able to read the local Json file in HTML page that work for chrome and IE.
Is there is any way to do it without using any web server.
Let's say you have,
index.html & sample.json in the same folder,
you can do this,
$http.get('sample.json').then(function(response) {
console.log(response);
});
of course you will need to run this from a controller, stand alone or in a directive, etc.
I found this solution on the web, i didn't try it but according to the comments it should work
function loadJSON(callback) {
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', 'my_data.json', true); // Replace 'my_data' with the path to your file
xobj.onreadystatechange = function () {
if (xobj.readyState == 4 && xobj.status == "200") {
// Required use of an anonymous callback as .open will NOT return a value but simply returns undefined in asynchronous mode
callback(xobj.responseText);
}
};
xobj.send(null);
}
The function above will create a new instance of a XMLHttpRequest and load asynchronously the contents of my_data.json. I have gone with asynchronous but you can change the argument to false if you want a synchronous load. Thankfully all modern browsers support the native JSON.parse method. Remember our anonymous callback? here's how you use it.
function init() {
loadJSON(function(response) {
// Parse JSON string into object
var actual_JSON = JSON.parse(response);
});
}``
http://codepen.io/KryptoniteDove/post/load-json-file-locally-using-pure-javascript
Create a JSON file named sample.json in a translation folder .Then in controllers use the below code to get the values present in JSON file
$http.get('translation/sample.json').success(function(response){
console.log(response);
});
or
$.getJSON('translation/sample.json', function(data){
console.log(data);
});

How to restore/reuse json serialized objects in fabricjs?

I am trying to create a collaborative whiteboard with socket.io and fabric.js.
When a user draws something I send the path to other users as a JSON format:
canvas.on('path:created', function(e) {
canvas.remove(fabric.Path.fromObject(JSON.stringify(e.path)));
socket.emit('add path', e.path.toJSON());
});
How can I recreate this object on the canvas here?
socket.on('add path', function(path) {
canvas.add(path); // doesn't work
});
try to use fabric.util.enlinvenObjects
The purpouse of that function is to switch from object form to istance.
socket.on('add path', function(path) {
fabric.util.enlivenObjects([path], function(objects) {
objects.forEach(function(o) {
canvas.add(o);
});
});
});
For those calling this function in a TypeScript project...
In my case setting namespace to empty string ('') and explicitly typing the callback argument made the function work smoothly.
fabric.util.enlivenObjects(
action.payload.objects,
(enlivedObjects: fabric.Object[]) => {
canvas.add(...enlivedObjects);
canvas.renderAll();
},
'');

AngularJS $http and filters

I have a JSON file, which contains:
{
"/default.aspx": "headerBg",
"/about.aspx": "aboutBg",
"/contact.aspx": "contactBg",
"/registration.aspx": "regBg",
"/clients.aspx": "clientsBg",
"/onlinesessions.aspx": "bg-white-box",
"/ondemamdsessions.aspx": "bg-grey"
}
Now I am reading this json file using $http, but I want to add a filter in below fashion:
Using window.location.pathname, I am reading path of the current page, suppose the current page is /about.aspx
Then I want to add a filter in $http response by which I want to read only aboutBg.
The code I wrote can retrieve all the values, but unable to filter that. Please help.
User this function where you receive the response.
function getPageBgClass(currentPage, responseData) {
if (responseData.hasOwnProperty(currentPage))
return responseData[currentPage]
else
return "none"
}
Here is how it should be used in your promise then function
function(response) {
var bg = getPageBgClass(window.location.pathname, response.data);
//Your code here ...
}
there is no direct method to get key using value from json.
you should make sure that there are no 2 keys having same value for below code to work
function swapJsonKeyValues(input) {
var one, output = {};
for (one in input) {
if (input.hasOwnProperty(one)) {
output[input[one]] = one;
}
}
return output;
}
var originaJSON = {
"/default.aspx": "headerBg",
"/about.aspx": "aboutBg",
"/contact.aspx": "contactBg",
"/registration.aspx": "regBg",
"/clients.aspx": "clientsBg",
"/onlinesessions.aspx": "bg-white-box",
"/ondemamdsessions.aspx": "bg-grey"
}
var invertedJSON = swapJsonKeyValues(originaJSON);
var samplepathname = "aboutBg";
var page = invertedJSON[samplepathname];
[function swapJsonKeyValues from https://stackoverflow.com/a/1970193/1006780 ]

Ember.js Component properties data set by Ajax JSON

I have a Component that has an injected service, which makes an Ajax call. I can receive the JSON data successfully and can dump it into the console after the promise "THEN" returns.
Here's my component. I can see the dumped data, but how do I set the component properties with that JSON and have it accessible in the template? Also, why can't I use "this.get" in my function below?
import Ember from 'ember';
export default Ember.Component.extend({
attr_types: Ember.inject.service('svc-attrtypes'),
atype_list: [],
actions: {
getATypes: function() {
this.get('attr_types').getTypes().then(function(json){
console.log(json);
this.atype_list = json;
console.log(this.atype_list);
// below returns: TypeError: this.get is not a function
this.get('atype_list').pushObjects(json);
});
}
}
});
In my template I have this:
{{#each atype_list.alltypes as |a|}}
<li>{{a.attr_type}} - {{a.attr_type_desc}}</li>
{{/each}}
If I manually place my JSON into the atype_list it shows perfectly on the template. But if I try to set it after my Ajax returns, nothing shows, except for in the console output.
I appreciate any help. I am sure I a missing something simple. ( or more likely, I'm just going about this all wrong)
This changed with anonymous function passed to then. You have to save this or use es6 arrow function syntax.
import Ember from 'ember';
const { service } = Ember.inject;
export default Ember.Component.extend({
attrTypes: service('svc-attrtypes'),
atypeList: [],
actions: {
// es6 version
getATypes(){
this.get('attrTypes').getTypes().then(array => {
this.set('atypeList', array); //replaces original array
this.get('atypeList').pushObjects(array); // adds array's elements to the end
});
}
// es5 version
getATypes: function () {
var _this = this;
this.get('attrTypes').getTypes().then(function(array){
_this.set('atypeList', array);
}
}
}
});
You wrote that you are new to ember, so I added little more syntax sugar. Also check ember-cli if you don't know about that already.

Sending anonymous functions through socket.io?

I want to create a client-side function that can receive and execute arbitrary commands using client-side variables. I will be sending these functions from my server by using socket.io to send a JSON object containing an anonymous function which will be my command. It looks something like the following:
//client side
socket.on('executecommand', function(data){
var a = "foo";
data.execute(a); //should produce "foo"
});
//server side
socket.emit('executecommand', {'execute': function(param){
console.log(param);
}});
Yet, when I tried it out, the client side received an empty json object (data == {}), then threw an exception because data contained no method execute. What is going wrong here?
JSON doesn't support the inclusion of function definitions/expressions.
What you can do instead is to define a commands object with the functions you need and just pass a commandName:
// client-side
var commands = {
log: function (param) {
console.log(param);
}
};
socket.on('executecommand', function(data){
var a = 'foo';
commands[data.commandName](a);
});
// server-side
socket.emit('executecommand', { commandName: 'log' });
You can also use fn.apply() to pass arguments and check the commandName matches a command with in:
// client-side
var commands = { /* ... */ };
socket.on('executecommand', function(data){
if (data.commandName in commands) {
commands[data.commandName].apply(null, data.arguments || []);
} else {
console.error('Unrecognized command', data.commandName);
}
});
// server-side
socket.emit('executecommand', {
commandName: 'log',
arguments: [ 'foo' ]
});
You can't send literal JavaScript functions and expect it to work. You'll need to stringify the function first (i.e put it within a set of quotes), then eval the string on the client side.