obtain information from API javascript - javascript

I wanted to know if there was a way I can receive information from API through JavaScript. I'm currently trying to use the information from API from www.openweathermap.org but I'm not sure how I can do it with JS. I currently tried
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://api.openweathermap.org/data/2.5/weather?
lat=38.892634199999996&lon=-77.0689154", false);
xhr.send();
console.log(xhr);
which responds and sends me information in JS Object format:
{ response: {"coord":{"lon":-77.04,"lat":38.9},"weather":[{"id":800,"main":"Clear",
"description":"sky is clear","icon":"01d"}],"base":"cmc stations","main":{
"temp":301.51,"pressure":1016,"humidity":51,"temp_min":299.15,"temp_max":304.15},
"wind":{"speed":2.6,"deg":360},"clouds":{"all":1},"dt":1436565479,
"sys":{"type":1,"id":1325,"message":0.008,"country":"US","sunrise":1436521925,
"sunset":1436574893},"id":4140963,"name":"Washington, D. C.","cod":200}\n',
responseText: '{"coord":{"lon":-77.04,"lat":38.9},"weather":[{"id":800,
"main":"Clear","description":"sky is clear","icon":"01d"}],"base":"cmc stations",
"main":{"temp":301.51,"pressure":1016,"humidity":51,"temp_min":299.15,
"temp_max":304.15},"wind":{"speed":2.6,"deg":360},"clouds":{"all":1},
"dt":1436565479,"sys":{"type":1,"id":1325,"message":0.008,"country":"US",
"sunrise":1436521925,"sunset":1436574893},"id":4140963,"name":"Washington, D. C.","cod":200} }
I tried console.log(xhr.response.coord) and console.log(xhr.responseText.coord) as an example and both comes out undefined. Do I need to do something else to print out the information?
I know you can use $.get(URL, function()) to receive the information via JQUERY but is there a way I can do it just JS?

You should parse the string as a JSON object. Like this:
var data = JSON.parse(xhr.response);
console.log(data.coord);

You are missing the response handler
var xhr = new XMLHttpRequest();
// when the async call finishes, we need to check what happened
xhr.onreadystatechange=function(){
// if it finished without errors
if (xhr.readyState==4 && xhr.status==200){
// we get the data
var data = JSON.parse(xhr.responseText);
// this should be your json
//console.log(data.response.coord);
document.getElementById('response').innerHTML = xhr.responseText;
}
};
// NOTE! for demo purposes I'm using another api query that does not require an api key, change this to your api url
xhr.open("GET", "http://api.openweathermap.org/data/2.5/weather?q=London,uk", false);
xhr.send();
<div id="response"></div>

Your response is in JSON so you need to parse it first.
Use JSON.parse(xhr.response) to parse the response.
Like this:
JSON.parse(xhr.response)["coord"]["lat"]
JSON.parse(xhr.response)["coord"]["lon"]

Related

How to parse external json request and put it into a variable?

I'm very new to coding, I'm hoping someone can help me. I have this little bit of code, I am trying to learn this process:
Call Made to URL via GET request (json)
Parse the response from the GET request
Save the response into a variable that I will use later
Any and all help is appreciated!
const XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
const awsURL = 'https://cors.io/?http://status.aws.amazon.com/data.json';
function Get(awsURL){
var request = new XMLHttpRequest();
request.open("GET", awsURL, false);
request.send(null);
return request.responseText;
}
var AWSJson = JSON.parse(Get(awsURL));
console.log("Archived Outages: "+AWSJson.service_name);
Return value in given address is not in correct json format. Enter the url in your browser and check the output !

Javascript / Json Requested Object returns null

i'm trying to access a local JSON File with JS, turn it into an JS Object by parsing it and logging it to the console. I'm using Live Server in VS Code to set up the Server, therefore the localhost URL.
var requestURL = "http://localhost:5500/sqVol.json";
var request = new XMLHttpRequest();
request.open('GET', requestURL);
request.responseType = 'json';
request.send();
var jsonObj = request.response;
request.onload = function () {
JSON.parse(jsonObj);
logData(jsonObj);
};
function logData(jsonObj){
console.log("jsonObj= " + jsonObj);
//console.log("jsonObj[Datum]= " + jsonObj[Datum]);
//console.log("jsonObj.Datum= " + jsonObj.Datum);
}
Output: jsonObj= null
The JSON File:
{
"Datum": ["03.05.2017","05.06.2017"],
"Volume": [1338,1445]
}
Here's what I imagine happens:
I'm getting the Answer from localhost and parsing it via JSON.parse into an JS Object. As soon as the request finished im calling my logData function and passing the parsed Data to log it.
As #connexo pointed out I didn't understand the asynchronous nature of the call. And frankly i still don't but i guess a good starting points will be:
How do I return the response from an asynchronous call?
MDN Synchronous and Asynchronous Requests
As #Mani Kumar Reddy Kancharla pointed out my response is already a JS Object since i declared request.responseType = 'json';
This is how it looks right now:
var requestURL = "http://localhost:5500/sqVol.json";
var request = new XMLHttpRequest();
request.open('GET', requestURL);
request.responseType = 'json';
request.send();
request.onload = function () {
console.log(request.response);
var jsonObj = request.response;
logData(jsonObj);
};
function logData(jsonObj){
console.log("jsonObj= " + jsonObj);
console.log("jsonObj[Datum]= " + jsonObj.Datum);
Ouput: {…} ​
Datum: Array [ "03.05.2017", "05.06.2017" ] ​
Volume: Array [ 1338, 1445 ] ​
jsonObj= [object Object]
jsonObj[Datum]= 03.05.2017,05.06.2017
As you can see i can also access the .Datum Property. I Consider it solved. Thank you!
edit: Added the link provided by connexo.
I used the browser XMLHttpRequest object for Ajax about 12 years ago.
https://api.jquery.com/jquery.getjson/
You have two issues in your code:
You're using JSON.parse() too many times on same date which is already converted from JSON string to a JavaScript object and tries to parse a Javascript object raising a Syntax error. You've already mention request.responseType = 'json' i.e. responseType specifies you're receiving a JSON string as response so JavaScript Engine will already parse it and provide you a JavaScript object as request.response and you need not parse it. So you could use JSON.parse(request.responseText) if you want to parse it yourselves or directly use request.response as a JavaScript object.
You're trying to store request.response into a variable outside the load function which will just provide the value of request.response at that time which could be null if the response is not received yet. You need to get the response in the onload fucntion implementation as it is executed once you receive the response.
So what you're looking for overall is this ->
var requestURL = "http://localhost:5500/sqVol.json";
var request = new XMLHttpRequest();
var jsonObj;
function logData(jsonObj){
console.log("jsonObj= " + JSON.stringify(jsonObj));
console.log("jsonObj[Datum]= " + JSON.stringify(jsonObj["Datum"]));
console.log("jsonObj.Datum= " + JSON.stringify(jsonObj.Datum));
// or simply
console.log(jsonObj);
console.log(jsonObj['Datum']);
console.log(jsonObj.Datum);
}
request.onload = function () {
jsonObj = request.response;
logData(jsonObj);
};
request.responseType = 'json';
// finally send the request
request.open('GET', requestURL);
request.send();
Here JSON.stringify() converts a JavaScript Object back to a JSON string.
Refer to this link to get more information on how to use XMLHttpRequest
EDIT: Referring to another answer posted, people simply use libraries like jQuery AJAX to make asynchronous requests to get data from the web, especially in XML or JSON format.

Access parameters in a XMLHttpRequest Google Apps Script

I am currently trying to access the parameters of a POST request using Google Apps Script. I can logger the params object using e.parameter though i cannot seem to access the keys of the object by by using e.parameter.name.
XMLHttpRequest
var http = new XMLHttpRequest();
var url = "myappURL";
var params = JSON.stringify({employeeStatus: "Active", name: "Henry"});
http.open("POST", url, true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
//Call a function when the state changes.
http.onreadystatechange = function() {
// call back function
} // end callback
http.send(params);
Google Apps Script
function doPost(e) {
if (typeof e !== 'undefined') {
Logger.log(e.parameter.name); // does not work (undefined)
} // end if
} // end doPost
There are subtle quirks with the different ways data is posed via http. For instance I notice that you are using Content-type "application/x-www-form-urlencoded" when the usual header for json data is Content-Type: application/json.
I added a line that just returns the contents of the e variable so you can see what is returned.
I used curl to debug it with the following command.
curl -H "Content-Type: application/json" ---data "{status:123}" https://script.google.com/macros/s/AKfycbyJ38V-HpG7A-DxIBpik4HJ89fAtnCemCJ7ZXeFEL8KPEuGsR8/exec
The response I received was:
{"parameter":{},"contextPath":"","contentLength":12,"queryString":null,"parameters":{},"postData":{"length":12,"type":"application/json","contents":"{status:123}","name":"postData"}}
You can see that in my case the json was returned in the contents field rather than the parameters.
You could try this with your script to see what you get. You could also try changing the Content-Type.
After Further testing I think you would be better submitting your fields a form data rather than json. I have been able to get the paramer back by amending your javascript to:
var http = new XMLHttpRequest();
var url = "https://script.google.com/macros/s/AKfycbyJ38V-HpG7A-DxIBpik4HJ89fAtnCemCJ7ZXeFEL8KPEuGsR8/exec";
var params = "employeeStatus='Active'&name='Henry'";
http.open("POST", url, true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
//Call a function when the state changes.
http.onreadystatechange = function() {
if (http.readyState==4) {
//alert the user that a response now exists in the responseTest property.
console.log(http.responseText);
// And to view in firebug
// console.log('xhr',xmlhttp)
}
} // end callback
http.send(params);

How to read JSON data, that is sent from Android, using Javascript?

I have created a mobile application that scans the surrounding Bluetooth devices and I am able to put the devices into an array list.
Now, using the http POST method, I have to send a JSONObject having this array list to a url and even for this I have written an expected code on the android app(I am sure this code will work because I have already worked on this using POST method to URL's and displaying the response on the activity).
But, how to listen the JSONObject, sent by any android app to the URL, parse it and show it on that particular URL's webpage ?
(In short I am looking for a Javascript code which can handle this and show the list.)
if you already have the URL where the JSON is being posted to you can do:
plain js:
var request = new XMLHttpRequest();
request.open('GET', 'URL', true);
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
// Success!
var data = JSON.parse(request.responseText);
} else {
// We reached our target server, but it returned an error
}
};
request.onerror = function() {
// There was a connection error of some sort
};
request.send();
with jquery:
var getData = $.getJSON('URL');
getData.done(function(data){
// you have access to data here
});

How to parse JSONP response returned by api.themoviedb.org?

I'm using themoviedb.org API to fetch the movie info. This is the code I'm using:
var req = new XMLHttpRequest();
req.open("GET", "http://api.themoviedb.org/2.1/Movie.search/en/json/XXX/immortals?callback=foobar", true);
req.send();
req.onreadystatechange=function() {
if (req.readyState==4 && req.status==200) {
console.log(req.responseText);
}
}
And I'm getting this response in the console:
foobar([{"score":null,"popularity":3,"translated":true,"adult":false,"language":"ru","original_name":"Immortals","name":"Immortals","alternative_name":"\"War of the Gods\"","movie_type":"movie","i".......}])
How do I parse this response to get the name attribute?
Updates:
Thank you everybody but the actual answer was given by hippietrail.
eval(req.responseText)
More details: Filtering to specific nodes in JSON - use grep or map?
add this function to your page :
( i see its an array - so i'll iterate each item... - if you want the first one only - so please specify.)
function foobar(x)
{
$.each(x, function ()
{
alert(this.score);
});
}
http://jsbin.com/ojomej/edit#javascript,html
The URL you're using is for a JSONP call (see: http://en.wikipedia.org/wiki/JSONP). JSONP is used when cross domain request through XMLHttpRequest are not allowed. But you're using XMLHttpRequest already so I believe you don't need a JSONP call. So, if you remove the querystring from the URL:
var req = new XMLHttpRequest();
req.open("GET", "http://api.themoviedb.org/2.1/Movie.search/en/json/XXX/immortals", true);
req.onreadystatechange=function() {
if (req.readyState==4 && req.status==200) {
console.log(req.responseText);
}
}
req.send();
You should get a JSON string:
[{"score":null,"popularity":3,"translated":true,"adult":false,"language":"ru","original_name":"Immortals","name":"Immortals","alternative_name":"\"War of the Gods\"","movie_type":"movie","i".......}]
That you can parse using JSON.parse (see: https://developer.mozilla.org/en/JSON):
var data = JSON.parse(req.responseText);
Now you have a JavaScript object, in your case an array of objects, that you can use:
console.log(data[0].name) // "Immortals"
However, because the question is tagget "jquery", if you're using that library you can simplify a lot:
$.getJSON("http://api.themoviedb.org/2.1/Movie.search/en/json/XXX/immortals", function (data) {
console.log(data[0].name)
});
jquery will also take care of the browsers differences (e.g if the browser doesn't support JSON object).
Hope it helps.
I don't have an API key to test this, but it seems you're not very familiar with either jQuery nor JSON. Anyway something like this might get you started:
$.getJSON("http://api.themoviedb.org/2.1/Movie.search/en/json/XXX/immortals?callback=?",
function(data) {
alert(data[0].name);
}
);

Categories