I'm getting undefined when accessing JSON attribute - javascript

I'm using Parse Server, and in the Cloude Code, before save, I want to get a json from an api.
I'm using XMLHttpRequest to get a json, and here's the result of the json formatted:
This is my code to get the json:
var getJSON = function(url, requisicaoAceita, requisicaoFracassou) {
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'json';
xhr.onload = function() {
if(xhr.status!=200){
requisicaoFracassou(xhr.responseText);
}else{
requisicaoAceita(xhr.responseText);
}
};
xhr.send();
};
getJSON(url,
function(xhr){
var resultado = xhr;
console.log(resultado);
console.log(resultado.result);
},
function(xhr){
console.log("Error");
}
);
In the first output console.log(resultado) I get the result correctly, but in the second console.log(resultado.result) i get undefined, why is that?
Thanks :)

You did use .responseText instead of .response which would take into account the chosen responseType. Your resultado is still a JSON string, not an object with a result property

Thanks for help-me Shubham Khatri
parse the result before using
console.log(JSON.parse(resultado).result);
After doing this, worked!
var resultado = JSON.parse(xhr);
console.log(resultado.result);

Related

How do I get a specific key value from JSON object

This is my first time using any kind of APIs, and I'm just starting out in JS. I want to get the status of a server within a server hosting panel, to do this I need to log in (API/Core/Login), get a the value of a key called sessionID, then send that value to /API/Core/GetUpdates to get a response. When trying to pass the sessionID to GetUpdates, it sends undefined instead of the sessionID, I'm guessing I'm doing something wrong when trying to reference the key value. Here's my code:
var loginurl = "https://proxyforcors.workers.dev/?https://the.panel/API/ADSModule/Servers/83e9181/API/Core/Login";
var loginRequest = new XMLHttpRequest();
loginRequest.open("POST", loginurl);
loginRequest.setRequestHeader("Accept", "text/javascript");
loginRequest.setRequestHeader("Content-Type", "application/json");
loginRequest.onreadystatechange = function() {
if (loginRequest.readyState === 4) {
console.log(loginRequest.status);
console.log(loginRequest.responseText);
}
};
var logindata = '{"username":"API", "password":"password", "token":"", "rememberMe":"true"}';
loginRequest.send(logindata);
var statusurl = "https://proxyforcors.workers.dev/?https://the.panel/API/ADSModule/Servers/83e9181/API/Core/GetUpdates";
var statusreq = new XMLHttpRequest();
statusreq.open("POST", statusurl);
statusreq.setRequestHeader("Accept", "text/javascript");
statusreq.setRequestHeader("Content-Type", "application/json");
statusreq.onreadystatechange = function() {
if (statusreq.readyState === 4) {
console.log(statusreq.status);
console.log(statusreq.responseText);
}
};
var statusdata = `{"SESSIONID":"${loginRequest.responseText.sessionID}"}`; // Line I'm having problems with
statusreq.send(statusdata);
console.log(loginRequest.responseText.sessionID)
Here's the response of /API/Core/Login
{"success":true,"permissions":[],"sessionID":"1d212b7a-a54d-4e91-abde-9e1f7b0e03f2","rememberMeToken":"5df7cf99-15f5-4e01-b804-6e33a65bd6d8","userInfo":{"ID":"034f33ba-3bca-47c7-922a-7a0e7bebd3fd","Username":"API","IsTwoFactorEnabled":false,"Disabled":false,"LastLogin":"\/Date(1639944571884)\/","GravatarHash":"8a5da52ed126447d359e70c05721a8aa","IsLDAPUser":false},"result":10}
Any help would be greatly appreciated, I've been stuck on this for awhile.
responseText is the text representation of the JSON response.
Either use JSON.parse(logindata.responseText) to get the JSON data or use logindata.responseJSON

How to remove unwanted characters from JSON request

I am new to javascript.
I am facing this issue where I get [{"_id":1}] as my results.
Does anyone know how can I get 1 as my output?
This is my code, I am calling it from a database.
function getaccountid() {
var accID = new XMLHttpRequest();
accID.open('GET', "http://127.0.0.1:8080/account" + "/" + sessionStorage.getItem("username"), true);
accID.setRequestHeader("Content-Type", "application/json");
accID.send(JSON.parse);
accID.onload = function () {
sessionStorage.setItem("accountId", accID.response)
}
}
That response type is a JSON formatted string, it's a standard response type, not an issue. To read the value you need to parse the result from a JSON string to an array of objects, then access it.
Also note that you need to remove the JSON.parse reference within the send() call and define the load event handler before you send the request. Try this:
function getaccountid() {
var accID = new XMLHttpRequest();
accID.addEventListener('load', function() {
let responseObject = JSON.parse(this.responseText);
sessionStorage.setItem("accountId", responseObject[0]['_id']);
console.log(responseObject[0]['_id']); // = 1
});
accID.open('GET', "http://127.0.0.1:8080/account/" + sessionStorage.getItem("username"), true);
accID.setRequestHeader("Content-Type", "application/json");
accID.send();
}

Unable to get JSON output from XMLHttpRequest

I've read a few StackOverflow posts, googled it but still can't get what I want.
I simply want to get a JSON from Google's API and import it to a variable so I can filter it the way I want, the following code is what I have so far:
<!DOCTYPE html>
<html>
<body>
Term: <input type="text" id="field1" value="Mc Donalds in New York"><br>
<button onclick="myFunction()">Search</button>
<script>
function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
xhr.open(method, url, true);
xhr.responseType = 'json';
} else if (typeof XDomainRequest != "undefined") {
xhr = new XDomainRequest();
xhr.open(method, url);
xhr.responseType = 'json';
} else {
xhr = null;
}
return xhr;
}
function myFunction() {
var termo = document.getElementById("field1").value;
var URL = "https://maps.googleapis.com/maps/api/place/textsearch/json?query="+termo.replace(" ","+")+"&key=HIDDEN_KEY";
var data = createCORSRequest('GET',URL);
if (!data) {
throw new Error('CORS not supported');
}
}
</script>
</body>
</html>
When I do:
console.log(data);
I get:
When I do:
JSON.parse(data.responseText);
I get:
Uncaught DOMException: Failed to read the 'responseText' property from
'XMLHttpRequest': The value is only accessible if the object's
'responseType' is '' or 'text' (was 'json').
What should I get on console.log:
https://pastebin.com/4H7MAMcM
How can I get the JSON from XMLHttpRequest correctly?
Also worth mentioning, I'm using Cross-Origin Resource Sharing (CORS) because I couldn't access the domain from my local IP.
--Edit--
Phil thought this was a matter of not being able to return response from a asynchronous, but its wrong, I've tried using Ajax, XMLHttpRequest and now using CORS, the duplicate notation was incorrect, please remove it.
This behaviour is documented on MDN;
If responseType is set to anything other than the empty string or "text", accessing responseText will throw InvalidStateError exception.
Instead, you need to use the response property. Since you specified json as the responseType, response will be a JavaScript object (no need to JSON.parse it).
Aside from this, you'll also need to treat the AJAX request as asynchronous, rather than synchronous. For more info on that, see How do I return the response from an asynchronous call?.
Eventually, you should end up with something like;
function createCORSRequest(method, url, cb) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
xhr.open(method, url, true);
xhr.responseType = 'json';
xhr.onreadystatechange = function () {
if (this.readyState === 4) {
cb(this.response);
}
}
xhr.send(null);
} else if (typeof XDomainRequest != "undefined") {
xhr = new XDomainRequest();
xhr.open(method, url);
xhr.responseType = 'json';
} else {
xhr = null;
}
return xhr;
}
createCORSRequest('POST', '/echo/json/', function (response) {
console.log(response);
});
https://jsfiddle.net/ez3xt6ys/
However, the browser support seems patchy for this at best; https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/response. Instead, it is more common to see the responseType being left as text, and for people to JSON.parse() the responseText property.

Access json string in JavaScript

I have a String called json which has ArrayList values. I used Gson to convert the arraylist to json. I am passing the json to a javascript from servlet as a response in POST.
I get the response in js as ["1.343","73.6544","32.6454","34.453","43.565","23.454"]. How to access these values in js with a variable individually(these are location coordinates). I want to use these values to display the location in my map.
How do i access these values in js. The value obtained in js is a string which contains arraylist. I used gson to convert to string.
This is js:
<script>
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
var data = xhr.responseText;
data.toString();
alert(data);
}
}
xhr.open('POST', 'GetLocationFromDB', true);
xhr.send(null);
</script>
The data is value from servlet.
SErvlet:
String json = new Gson().toJson(arraylist);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
Parse the response to Json and you will have access to the elements
var json = JSON.parse(data);
Read more on JSON.parse here. https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
As a simple test to should how JSON.parse works.
var x = JSON.parse('["1.343","73.6544","32.6454","34.453","43.565","23.454"]');
alert(x[0]) // alerts with 1.343
Here is what you should have.
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
var json = JSON.parse(xhr.responseText);
console.log(json);
//or if you like alerts
alert(json);
}
}
xhr.open('POST', 'GetLocationFromDB', true);
xhr.send();
You have to parse your data.
JSON.parse() for parsing a string of JSON text into a javascript Object and JSON.stringify for turing a Javascript object into JSON text.

JSON.parse fails in function, works in console

I have a simple script that does a cross site request and gets data from a GitHub gist. The data from the Github API is returned as a JSON string. To allow further modification of the data, I want it as a JSON object.
// Create the XHR object.
function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// XHR for Chrome/Firefox/Opera/Safari.
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
// XDomainRequest for IE.
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
// CORS not supported.
xhr = null;
}
return xhr;
}
var tmpJSON = "";
var gistData = "";
var gistID = "5789756";
var gitAPI = "https://api.github.com/gists/"
var gistQuery = gitAPI + gistID;
function incrementGist() {
gistData = createCORSRequest('GET', gistQuery);
gistData.send();
tmpJSON = JSON.parse(gistData.response);
}
In the html page, I have
<p><input type="button" value="Increment" OnClick="incrementGist()"></p>
If I actually hit the button, the error I get is:
Uncaught SyntaxError: Unexpected end of input
But if I subsequently open the console and run this:
var crap = JSON.parse(gistData.response);
it works just fine. This happens in both Firefox and Chrome. I really don't see why the JSON.parse command fails inside a function call, but not in the console. An actual page is set up here
The problem is that you're trying to read the response before the server answered.
You must read the response in a callback. For example :
gistData = createCORSRequest('GET', gistQuery);
gistData.onreadystatechange = function() {
if (gistData.readyState === 4) {
if (gistData.status === 200) {
tmpJSON = JSON.parse(gistData.response);
... use tmpJSON...
... which should not be called so as it is not JSON...
... maybe tmpObject ?
}
}
}
gistData.send();
That's because you are not waiting the request to actually finish. I don't know your API but try waiting the server response then parse your JSON. you could try with a SetTimeout first to see that it is working but you nee to do something like in jQuery with its' success:function(...) callback

Categories