I need to console.log this value:
the
Specifically location which is under geometry
right now I able to print this entire set of data with this javascript code:
var url='https://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&key=APIKEYHERE';
function Get(url){
var Httpreq = new XMLHttpRequest(); // a new request
Httpreq.open("GET", url, false);
Httpreq.send(null);
return Httpreq.responseText;
}
var json_obj = JSON.parse(Get(url));
console.log(json_obj.results);
This code will not work for anyone who is trying to live test because you need an API Key.
The problem that I run into is that when I try and
console.log(json_obj.results.0)
I get this error:
Does anyone know how to print this value?
To access ith element of an array:
results[i];
So you should use:
console.log(json_obj.results[0]);
Try this: (untested)
console.log(json_obj.results[0].geometry.location)
Related
I am brand new to javascript and have spent the past few hours trying to parse json data from an api url into my body in my html document. My only experience with APIs are with C# wrappers so this is new to me.
This is the API url: https://catfact.ninja/fact
I'm not sure where to go from here. I've been able to successfully pull the data I want, but I'm only able to print it to the console and I'm not sure how to pull that data into html. Here is my javascript code:
var HttpClient = function() {
this.get = function(aUrl, aCallback) {
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var anHttpRequest = new XMLHttpRequest();
anHttpRequest.onreadystatechange = function() {
if (anHttpRequest.readyState == 4 && anHttpRequest.status == 200)
aCallback(anHttpRequest.responseText);
}
anHttpRequest.open( "GET", aUrl, true );
anHttpRequest.send( null );
}
}
var client = new HttpClient();
client.get('https://catfact.ninja/fact', function(response) {
var vsplit = response.split("\"")
console.log(vsplit[3]);
$('body').html(document.write(vsplit[3]));
});
Thanks for any help, sorry if I seem dumb
The first issue you have is that the call to document.write in the html function will not produce the results you think. document.write is a synchronous write function that tries to inject a string into the DOM renderer at the point it's called. If you remove that, you should have more luck seeing something in the HTML, but you can also use the following.
The response from https://catfact.ninja/fact is the following.
{"fact":"Cats' eyes shine in the dark because of the tapetum, a reflective layer in the eye, which acts like a mirror.","length":109}
There's no need to split the response when the format is JSON. You can use JSON.parse to create a Javascript Object. For example.
// data will contain data.fact, and data.length
var data = JSON.parse(response);
// Without using jQuery, you can set the html of the body directly
var body = document.getElementsByTagName("body")[0];
body.innerHTML = data.fact;
How can I read and print out a plain text file on my server line by line in reverse using javascript? I would prefer to use javascript or jquery over php but have no idea how to accomplish something like this. So for instance if I had a file like
foo
bar
foobar
barfoo
I would like it to print out
barfoo
foobar
bar
foo
Using a http-Request:
function httpGet(theUrl)
{
var xmlHttp = null;
xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", theUrl, false );
xmlHttp.send( null );
return xmlHttp.responseText;
}
var content = httpGet("google.de"); //enter the Url of your text file here
var lines = content.split("\n");
var result = "";
for(var i=0; i<lines.length; i++)
result = lines[i] + "\n" + result;
alert(result);
Demo is here (displaying the source of http://google.de backwards)
You can do it using the FileReader API. I am not sure if its still in draft or not, but it works in Chrome as well as Firefox.
You will have to simply read the file as text using readAsText method. And then split() the string based on \n and then reverse() and join() again.
Here is a jsFiddle example.
Hi I am working Android application development using titanium studio.I have developed small application.my problem is that I can not access variable which is define inside the xhr.on load.I used following code:
xhr.onload = function()
{
var json = this.responseText;
var to_array = JSON.parse(json);
var to_count = to_array.length;
};
I want to access to_count and to_array outside onload function and pass it to another child window.For that I used following code:
var feedWin = Titanium.UI.createWindow({
url:'home/feed.js'
});//alert(to_count);
feedwin.to_array = to_array;
feedwin.to_count = to_count;
The XHR client is asychronous by default, which means that code will continue to execute while the XHR is running. If you have code that is dependent on your XHR being finished, then you will need to either call that code from within the onload function, or force the XHR to be synchronous by adding "false" as a third parameter to xhr.send() (I've found the first option to be the more reliable one, and more in line with what Titanium expects/feels is best practice, just FYI).
The best way to accomplish this is to initialize your feedWin in the onload. So, one of the following two snippets should work:
xhr.onload = function()
{
var json = this.responseText,
feedWin = Titanium.UI.createWindow({
url:'home/feed.js'
});//alert(to_count);
feedWin.to_array = JSON.parse(json);
feedWinto_count = to_array.length;
};
or
var feedWin = Titanium.UI.createWindow({
url:'home/feed.js'
});
xhr.onload = function()
{
var json = this.responseText,
feedWin.to_array = JSON.parse(json);
feedWinto_count = to_array.length;
};
I'm not familiar with Titanium, so I don't know particulars, but that is my best guess.
I am not very familiar with Titanium, but wrt to scope of declaration, I think this is what you need to do to use them outside the function.
var to_array;
var to_count;
xhr.onload = function()
{
var json = this.responseText;
to_array = JSON.parse(json);
to_count = to_array.length;
};
In my app I'm displaying 10 charts (charts are from dygraphs.) to monitor data. For displaying charts I'm getting data from my sever by sending ajax request to 4 servlets on every 5 seconds. After 10-15 mins (don't know exact time.) my browser crashes saying "aw!! snap." What could be the reason? Is it javascript that is causing it? or is it because I'm sending request every 5 seconds?
Browser tested: Firefox and Chorme.
Note:- When I refresh the browser after crash it again works fine for 10-15 mins.
JS code:
var i=0;
var loc = new String();
var conn = new String();
var heapUsage = new String();
var cpuUsage = new String();
var thrdCnt = new String();
var heapUsageConsole = new String();
var cpuUsageConsole = new String();
var thrdCntConsole = new String();
var user = new String();
var MemTotal = new String();
function jubking(){
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
var url = "MonitorDBServlet";
xmlhttp.open("POST", url, false);
xmlhttp.send(null);
var str = xmlhttp.responseText;
var strArr = str.split(",");
url = "MonitorTomcatServlet";
xmlhttp.open("POST", url, false);
xmlhttp.send(null);
var appstr = xmlhttp.responseText;
var appArr = appstr.split(",");
url = "MonitorConsoleTomcatServlet";
xmlhttp.open("POST", url, false);
xmlhttp.send(null);
var appstrConsole = xmlhttp.responseText;
var appArrConsole = appstrConsole.split(",");
url = "CpuMemoryServlet";
xmlhttp.open("POST", url, false);
xmlhttp.send(null);
var statesStr = xmlhttp.responseText;
var states = statesStr.split(",");
if(i>30){
loc = loc.substring(loc.indexOf("\n")+1);
loc += i+","+strArr[0]+","+strArr[1]+"\n";
//--- Do same thing all other var
} else {
loc += i+","+strArr[0]+","+strArr[1]+"\n";
//--- Do same thing all other var
}
document.getElementById("dbSize").innerHTML = strArr[3];
document.getElementById("HeapMemoryUsageMax").innerHTML = appArr[1];
document.getElementById("HeapMemoryUsageMaxConsole").innerHTML = appArrConsole[1];
g = new Dygraph(document.getElementById("dbLocks"),
",locksheld,lockswait\n"+loc+"");
g = new Dygraph(document.getElementById("activeConnection"),
",Connections\n"+conn+"");
g = new Dygraph(document.getElementById("example2"),
",heapUsage\n"+heapUsage+"");
g = new Dygraph(document.getElementById("example3"),
",cpuUsage\n"+cpuUsage+"");
g = new Dygraph(document.getElementById("example4"),
",thread,peakThread\n"+thrdCnt+"");
g = new Dygraph(document.getElementById("example6"),
",heapUsage\n"+heapUsageConsole+"");
g = new Dygraph(document.getElementById("example7"),
",\n"+cpuUsageConsole+"");
g = new Dygraph(document.getElementById("example8"),
",thread,peakThread\n"+thrdCntConsole+"");
g = new Dygraph(document.getElementById("cpuStates"),
",user,system,nice,idle\n"+user+"");
g = new Dygraph(document.getElementById("memStates"),
",MT,MF,B,C,ST,SF\n"+MemTotal+"");
i = i + 1;
setTimeout("jubking()", 5000);
}
You can use about:crashes in FF to view the specific reason for your crash. As mentioned by others, you could be leaking memory if you're caching off data (assigning it to a variable) returned by your AJAX call and not clearing it when the next call is made.
Edit:
Just saw your comment - 1,923,481 K is definitely too much - you're leaking data somewhere. What OS are you running? If you run FF from console in *nix, you usually get some form of a dump into console when something's going wrong (not sure about Windows).
You could possibly try decreasing your poll intervals to once every few seconds and step through the script using Firebug or Chrome's debugger to see what's happening. Worst case, start commenting things out until you figure out exactly what is making your app crash. And then, figure out a way to fix it :)
I suspect that your dygraphs usage is, as you note in your comments, the source of your trouble. It looks like you're binding new graphs over and over again when you only want to update the data, using a moving window for the data would also help. Try reworking your updater to work like this pseudo-JavaScript:
var graphs = {
dbLocks: {
graph: new DyGraph(/* ... */),
data: [ ]
},
activeConnection: {
graph: new DyGraph(/* ... */),
data: [ ]
},
// etc.
};
var DATA_WINDOW_SIZE = 1000; // Or whatever works for you.
function update(which, new_data) {
var g = graphs[which];
g.data.push(new_data);
if(g.data.length > DATA_WINDOW_SIZE)
g.data.shift();
g.graph.updateOptions({ file: g.data });
}
function jubking() {
// Launch all your AJAX calls and bind a callback to each
// one. The success callback would call the update() function
// above to update the graph and manage the data window.
// Wait for all the above asynchronous AJAX calls to finish and
// then restart the timer for the next round.
setTimeout(jubking, 5000);
}
The basic idea is to use window on your data with a reasonable maximum width so that the data doesn't grow to chew up all your memory. As you add a new data point at the end of your data cache, you drop old ones off the other end once you hit your maximum comfortable size.
You can find some techniques for waiting for several asynchronous AJAX calls to finish over here: How to confirm when more than one AJAX call has completed? (disclosure: yes, that's one of my other answers).
The answer above advocates re-using your Dygraph object and calling g.updateOptions({file:...}) to reduce memory usage. This is a great way to do it.
The other way is to call g.destroy() before you redefine the Dygraph object. This will make dygraphs clear out all of its internal arrays and DOM references. Example:
g = new Dygraph(...);
g.destroy();
g = new Dygraph(...);
Read more here: http://blog.dygraphs.com/2012/01/preventing-dygraphs-memory-leaks.html
This should be a very simple concept, but I just don't understand. In a Titanium app I have an array of data used by several windows, my xhr result needs to be passed to the top level of my app's namespace to be added to the array. I can successfully parse the JSON response inside of the onload function, but I want to separate my data code from my UI generation.
Here is a simplified app.js version so that I might be able to understand the concept. And no, I won't pollute the global namespace in my real app.
Titanium.UI.setBackgroundColor('#000');
var myArray = [];
var xhr = Titanium.Network.createHTTPClient();
xhr.onload = function() {
myArray = JSON.parse(this.responseText);
// var data = JSON.parse(this.responseText); // no help
// myArray.push(data); // no help
// return myArray; // no help
};
xhr.onerror = function() {
Titanium.UI.createAlertDialog({ message:"Something has gone terrible wrong."});
};
xhr.open('GET','http://myapp.com/data.json');
xhr.send();
var win = Ti.UI.createWindow();
var view = Titanium.UI.createView({
backgroundColor:'green'
});
var caption = myArray[2].caption;
var label = Ti.UI.createLabel({
color:'white',
text:caption,
textAlign:'center'
});
view.add(label);
win.add(view);
win.open();
Thanks for your patience!
Edit
This produces the the correct result from the user's perspective, but I want to access the array outside the scope of the onload function. I don't want to have UI code mixed with API calls.
xhr.onload = function() {
myArray = JSON.parse(this.responseText);
var caption = myArray[2].caption;
var label = Ti.UI.createLabel({
color:'white',
text:caption,
textAlign:'center'
});
view.add(label);
};
The code is being run asynchronously. The label is attempting to generate before the xhr.onload has begun.
you should fire an event from the onload method of your code.
the event will have a listener in the UI section of your application and it will provide the appropriate separation of http code from the ui code; Something like this
xhr.onload = function() {
myArray = Ti.App.fireEvent("app.updateLabel",
{"responseText":this.responseText});
};
in your UI, view code
Ti.App.addEventListener("app.updateLabel",function(data) {
myArray = JSON.parse(data.responseText);
var caption = myArray[2].caption;
var label = Ti.UI.createLabel({
color:'white',
text:caption,
textAlign:'center'
});
view.add(label);
});
more on events from appcelerator documentation
and I have some examples on my blog, http://blog.clearlyinnovative.com, also
I'm not exactly sure what you're asking but I do see an issue. You are creating a JSON object not an array with myArray = JSON.parse(this.responseText); An object doesn't have the .push() method so that explains the no help comment. I also noticed you defined it as an array then assigned a JSON object to it.