access jquery json data after load? - json

How do I access my data from outside the getJSON command?
//LOAD JSON
$.getJSON("users.js", function(data) {
numberOfPieces = data.users.length;
alert("Loaded "+numberOfPieces); // <------WORKS
});
//Select a piece
var pieceSelected = Math.floor(Math.random() * (numberOfPieces));
alert("pieceSelected: "+data.users[pieceSelected].Name); // <------RETURNS "data is not defined"
Thank you!

Your issue is that function parameters are scoped to that function and inaccessible outside of the function. By using a variable outside of the scope, things should work as expected.
var piecesData;
//LOAD JSON
$.getJSON("users.js", function(data) {
piecesData = data;
numberOfPieces = data.users.length;
alert("Loaded "+numberOfPieces); // <------WORKS
});
//Select a piece
var pieceSelected = Math.floor(Math.random() * (numberOfPieces));
alert("pieceSelected: "+ piecesData.users[pieceSelected].Name);

Related

Pass a random JSON pair into an aframe component

Edit 3: The code is now working across numerous objects (thanks to Noam) and he has also helped in getting the random function working alongside it. I'll update the code in the question once its implemented.
Edit 2: I've taken #Noam Almosnino's answer and am now trying to apply it to an Array with numerous objects (unsuccessfully). Here's the Remix link. Please help!
Edit: I've taken some feedback and found this page which talks about using a JSON.parse function. I've edited the code to reflect the new changes but I still can't figure out exactly whats missing.
Original: I thought this previous answer would help in my attempt to parse a json file and return a random string and its related pair (e.g Title-Platform), but I couldn't get it to work. My goal is to render the output as a text item in my scene. I've really enjoyed working with A-frame but am having a hard time finding documentation that can help me in this regard. I tried using the following modified script to get text from the Json file...
AFRAME.registerComponent('super', { // Not working
schema: {
Games: {type: 'array'},
jsonData: {
parse: JSON.parse,
stringify: JSON.stringify}
},
init: function () {
var el = this.el;
el.setAttribute('super', 'jsonData', {src:"https://cdn.glitch.com/b031cbf1-dd2b-4a85-84d5-09fd0cb747ab%2Ftrivia.json?1514896425219"});
var hugeArray = ["Title", "Platform",...];
const el.setAttribute('super', {Games: hugeArray});
el.setAttribute('position', {x:-2, y:2, z:-3});
}
});
The triggers are also set up in my html to render the text. My code is being worked on through glitch.com, any help will be much appreciated!
To load the json, I think you need to use an XMLHttpRequest (as Diego pointed out in the comments), when that's loaded, you can set the text through setAttribute.
Here's a basic example on glitch:
https://glitch.com/edit/#!/a-frame-json-to-text
On init it does the request, then when done, it set's the loaded json text onto the entity.
AFRAME.registerComponent('json-text-loader', {
schema: {},
init: function () {
var textEntity = document.querySelector('#text');
var url = 'json/text.json';
var request = new XMLHttpRequest();
request.open( 'GET', url, true );
request.addEventListener( 'load', function ( event ) {
var jsonText = JSON.parse( event.target.response )
textEntity.setAttribute("value", jsonText.text)
} );
request.send( null );
}
});
Updated version: https://glitch.com/edit/#!/peppermint-direction
AFRAME.registerComponent('json-text-loader', {
schema: {},
init: function () {
var textEntity = document.querySelector('#text');
var url = 'json/text.json';
var request = new XMLHttpRequest();
request.open( 'GET', url, true );
request.addEventListener( 'load', function ( event ) {
var games = JSON.parse( event.target.response ).games;
// Get a random game from the list
var randomGame = games[Math.floor(Math.random()*games.length)];
// Get the next game if it's available
var nextGame = null
if (games.indexOf(randomGame) < games.length - 1) {
nextGame = games[games.indexOf(randomGame) + 1]
}
// Build the string for the games
var gameInfo = randomGame.Title + '\n' + randomGame.Developer + '\n\n'
if (nextGame != null) {
gameInfo += nextGame.Title + '\n' + nextGame.Developer + '\n'
}
textEntity.setAttribute("value", gameInfo);
var sceneEl = document.querySelector('a-scene');
sceneEl.querySelector('a-box').setAttribute('material', {src:"https://cdn.glitch.com/4e63fbc2-a1b0-4e38-b37a-9870b5594af8%2FResident%20Evil.jpg?1514826910998"});
});
request.send( null );
}
});

How to get coordinates from a KML file?

Is there any way to parse a kml file and get the coordinates from it with JavaScript?
I've tried doing it with "getElementsByTagName" (like here) but debugger says it's not a valid function.
Any ideas?
It's not easy but you can import the file xml and the parsing with jquery parseXML
// import the file --- se related function below
var content = getSelectedFileContent(importFilename);
// build an xmlObj for parsing
xmlDocObj = $($.parseXML(content));
function getSelectedFileContent(filename) {
// var importFilename = importAreaBaseURL + filename;
var request = new XMLHttpRequest();
request.open("GET", filename, false);
request.send(null);
return request.responseText;
};
at this point you can easy parse the xml obj for placemark and iterate over them for the tag/value you need via jquery
var placemarks = xmlDocObj.find("Placemark");
placemarks.each(function (index) {
if ($(this).find("Polygon").length > 0) {
tipoGeom = "Polygon";
tmpHtml = $(this).find("Polygon").find("outerBoundaryIs").find("coordinates").html();
gmlll_geom = kmlCoords2gmlll( tmpHtml);
inner = $(this).find("Polygon").find("innerBoundaryIs");
inner.each(function(index,el) {
$(el).find("coordinates").html(); // this are the coordinates for polygion
});
}
});
These are sample parts (an extract of functioning code .... not all you need) this code is just for a suggestion....

Return json object from dojo.xhrget

I am trying to get the json object from a dojo xhrGet call.
What I want is jsonobject = stuff;
I can see the json object in the console, but cannot access it!
var xhrargs = {
url: "/rest/url",
handleAs: "json",
preventCache : false,
load: function(json_results){
console.log(json_results);
store = json_results;
return dojo.toJson.json_results;
},
error: function(response, ioArgs) {
console.error(response);
console.error(response.stack);
}
};
var deferred = dojo.xhrGet(xhrargs);
console.log("Json is "+JSON.stringify(deferred));
The console.log part that shows the json_results is fine, exactly what I want.
The dojo.xhrXXX methods are asynchronous. This means that the lines following
var deferred = dojo.xhrGet(xhrargs);
Will continue to execute while the call to an external endpoint is processing. This means you need to use the promise API to tell a certain block of code to execute once the XHR request is complete:
var deferred = dojo.xhrGet(xhrargs);
deferred.then(function(result){
//this function executes when the deferred is resolved (complete)
console.log('result of xhr is ',result);
});
Due to the asynchronous nature of the request, for most intents and purposes that value doesn't exist outside the scope of the callback function. One way to structure your code around this is in multiple blocks. for example:
var xhrLoaded = function(results){
console.log('results = ',results);
store = results;
}
var performXhr = function(){
var xhrargs = {
url: "/rest/url",
handleAs: "json",
preventCache : false,
error: function(response, ioArgs) {
console.error(response);
console.error(response.stack);
}
};
var deferred = dojo.xhrGet(xhrargs);
deferred.then(xhrLoaded);
}
performXhr();
You can still access variables outside of the scope of the function (for example if store were defined globally).
try this
var xhrArgs = {
url:"MethodName.action?Id="+id,
handleAs: "json",
load: function(Data){
var values = Data;
var count = Object.keys(values).length // gives u all keys count in a json object. In mine it is 0,1,2,3
for (var i =0; i<count; i++){
var temp = values[i]; // values['name']
// do somthing ..
}
}
},
error: function(error){
alert(error);
}
}
dojo.xhrPost(xhrArgs);

JSON.stringify gives me wrong json array

I have this code:
var sidebars = {};
var counter = 0;
// Loop through all already crated sidebars
$('.custom_dynamic_sidebars li').each(function(event) {
sidebars[counter] = $(this).text();
counter++;
});
var sidebars_string = JSON.stringify(sidebars);
but it gives me this string:
{\"0\":\"aa\",\"1\":\"bb\"}
Here is javascript which sends array to the server:
$.ajax({
url:"/welit_2/wp-admin/admin-ajax.php",
type:'POST',
data:'action=dynamic_sidebars&sidebars='+sidebars_string+'',
success:function(results) {
console.log(results);
}
});
does anyone know what am I doing wrong?
thx for your time
So I found a solution If you run stripslashes() on the JSON string before you output it, it works fine

Binding JSON string to ListView in Metro apps?

I have a metro application(HTML5 & WinJS) in which am trying to display service data . Actually here am retrieving JSON data from my service but am unable to bind this data into listview . Anyone give me some working example.
Thank you.
You can use the WinJS.xhr() for this. You can read more about it on this link https://msdn.microsoft.com/pt-br/library/windows/apps/br229787.aspx and here is an example:
var path = "data/file.json";
function getData(path) {
WinJS.xhr({ url: path }).then(
function (response) {
var json = JSON.parse(response.responseText);
// Since this is an asynchronous function, you can't
// return the data, so you can:
// 1) retrieve the data to a namespace once the app loads.
var list = new WinJS.Binding.List(json);
Somenomespace.data = list;
// 2) or do all the binding inside the function.
var listView = document.getElementById("listViewID");
listView.winControl.itemDataSource = list.dataSource;
});
}
If you use the built in JSON.parse(jsonString) function you can loop through the content using a normal for loop as it then is a normal object and add it as usuall. Just remember to process or render the data.
Her is an example from code i had in a search page using listview:
var response = JSON.parse(data) ;
var originalResults = new WinJS.Binding.List();
for (x in response) {
originalResults.push(response[x]);
}
this.populateFilterBar(element, originalResults);
this.applyFilter(this.filters[0], originalResults);