Javascript / Json Requested Object returns null - javascript
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.
Related
Issue with fetching and outputting data from API
I have recently learned to use APIS in code, but for my javascript version I've had to learn different ways of doing it, when using what should be the simplest method nothing gets outputted to my chrome console. const request = new XMLHttpRequest(); request.open('GET','apistuff, true); request.onload = function() { let data = JSON.parse(this.response); console.log(data); }; HTML file is just empty and calls the javascript file
Just replace current code with below code and let me know the status const request = new XMLHttpRequest(); request.open('GET', apistuff, true); request.send(); // we need to call this send method to open breach between server and client request.onload = function() { let data = JSON.parse(request.response); // if response is in text simply use **request.responseText** console.log(data); };
Function to access an API in JavaScript and doesn't return the required value [duplicate]
This question already has answers here: How do I return the response from an asynchronous call? (41 answers) Closed 4 years ago. I need a function in JavaScript that can access an API to get the latitude coordinate for a particular IP address. The current function can print the latitude in the console when called. When I return the value, it is returned as undefined. I cannot get the function to return the value I have accessed from the API. I have tried declaring the variable in numerous locations and have altered the function numerous times, but I cannot get the function to return or print anything but 'undefined' when outside of the internal function. // Code for function function latitude(ip) { var latitudeData; var access_key = '*******'; // Create a request variable and assign a new XMLHttpRequest object to it. var request = new XMLHttpRequest(); // Open a new connection, using the GET request on the URL endpoint request.open('GET', 'http://api.ipstack.com/' + ip + '?access_key=' + access_key, true); request.onload = function test () { // Begin accessing JSON data here latitudeData=data.latitude; console.log(latitudeData); // This will print required value. ** return latitudeData; } } // Send request request.send(); return test(); // get error from this line. } var ip = '134.201.250.155'; var p =latitude(ip); console.log(p); // This will print undefined **
It's possible the rest of your code is already executing before the request comes back. You can try to make the code synchronous to pause its execution before receiving the request. Example of a synchronous request from https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Synchronous_and_Asynchronous_Requests var request = new XMLHttpRequest(); request.open('GET', '/bar/foo.txt', false); // `false` makes the request synchronous request.send(null); if (request.status === 200) { console.log(request.responseText); } If you don't want to do that just keep your code logic inside of your request.onload function. Another option is to use an async function and await the return value. Example: In JavaScript how do I/should I use async/await with XMLHttpRequest?
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 !
obtain information from API 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"]
Retrieving audio from Web SQL Database and playing with Web Audio API
I have the code saving an ArrayBuffer (from an XMLHttpRequest call to get an mp3 as an arraybuffer) to a web sql database, retrieving it from a sql query which returns an object ArrayBuffer. However, when I try to decodeAudioData or createBuffer I get a type error. var buffer = audioContext.createBuffer(result.xtalk,false); gives an Uncaught TypeError: Type error if I put an alert in result.xtalk is object ArrayBuffer This is in Chrome 21.0.1180.75 on a mac I tried creating an ArrayBuffer and filling it byte by byte then passing that - but that didn't work either.
Check this tutorial.May this would help var dogBarkingBuffer = null; var context = new webkitAudioContext(); function loadDogSound(url) { var request = new XMLHttpRequest(); request.open('GET', url, true); request.responseType = 'arraybuffer'; // Decode asynchronously request.onload = function() { context.decodeAudioData(request.response, function(buffer) { dogBarkingBuffer = buffer; }, onError); } request.send(); } Refer the following link:- http://www.html5rocks.com/en/tutorials/webaudio/intro/ Also do "typeof" on the arraybuffer object you are receiving.Arraybuffer have a properties called byteLength. If its undefined that means the object you received from the sql database is not arraybuffer object Reference:-https://developer.mozilla.org/en-US/docs/JavaScript_typed_arrays/ArrayBuffer