How do I get a specific key value from JSON object - javascript

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

Related

Why does the api responds twice even though I have called once in JavaScript using XMLHttpRequest?

When I send the request then the first response is empty then it shows the JSON response twice. How can I solve this? Any advice will be helpful. Thanks :(
Code:
function go() {
var cat;
var api = new XMLHttpRequest();
var ip = document.getElementById(
"ipBox").value;
var finalUrl =
"http://ipwhois.app/json/" + ip;
api.open("GET", finalUrl);
api.send();
api.onreadystatechange = (e) => {
cat = api.responseText;
console.log(cat)
};
}
readyState has multiple possible values, including "loading" and "interactive", not just "complete". Use onload instead.

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();
}

Pull data from Bandsintown API

I need a little help on pulling events data from the Bandsintown API. I tested the HTTP GET request in the Postman App and it returns data correctly.
Now I am trying to pull this data into a JavaScript to then render it on a website that I design, but it seems that something does not work. Here's my code:
var eventRequest = new XMLHttpRequest();
eventRequest.open('GET', 'https://rest.bandsintown.com/artists/${artistname}/events?date=upcoming&app_id=${app_id}');
eventRequest.onload = function() {
var eventsData = eventRequest.responseText;
};
eventRequest.send();
To render the data further down in the JS I am using:
document.getElementById("app").innerHTML = `
${eventsData.map(eventTemplate).join("")}
`;
you can try this and in log might see further error.
var eventRequest = new XMLHttpRequest();
eventRequest.open("GET", "https://rest.bandsintown.com/artists/${artistname}/events?date=upcoming&app_id=${app_id}", true);
eventRequest.onreadystatechange = function (event) {
if (eventRequest.readyState === 4) {
if (eventRequest.status === 200) {
console.log(eventRequest.responseText)
} else {
console.log("Error", eventRequest.statusText);
}
}
};
eventRequest.send(null);
Also, I'm pretty sure that if you want to use string literals in your url (${artistname}) you will need back quote (``) instead of simple or double-quotes.
'https://rest.bandsintown.com/artists/${artistname}/events?date=upcoming&app_id=${app_id}'
to
`https://rest.bandsintown.com/artists/${artistname}/events?date=upcoming&app_id=${app_id}`

How to store and fetch data from hash tables - javascript

I couldn't find anything on javascript but this might be clarified very quickly. I am working on a website where I have to retrieve data via http requests from a server. Because I need to make several requests and the data is constant what I want to do is make table with keys and values -> store those values in a file -> and then be able to retrieve those values. That way I have to read one file as apposed to fetching data via 30 http requests
General Idea :
Given: spell id = number (Ex. 45)
Output: name of spell = string (Ex. fire...)
Use this output to then fetch the url of the image of the spell (containing the spell name)
EDIT
Code :
// When I fetch the file i use (json data)
function getChampionImage(id) {
var champUrl = "https://na.api.pvp.net/api/lol/static-data/na/v1.2/champion/" +id +"/?api_key=....."
xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", champUrl, false );
xmlHttp.send( null );
var jsonText = xmlHttp.responseText;
var champData = JSON.parse(jsonText);
var champName = champData.key;
return "http://ddragon.leagueoflegends.com/cdn/" + versionNum + "/img/champion/"+champName+".png";
}
all you need to do is tack the response onto an object, keyed by input.
this is especially simple in sync IO because you don't have to worry about callback scope.
Since functions are objects in JS, you can just use the procedure itself as a namespace, which plays well with methods because you don't need an outside variable:
// When I fetch the file i use (json data)
function getChampionImage(id) {
var cached=getChampionImage["_"+id];
if(cached) return cached;
var champUrl = "https://na.api.pvp.net/api/lol/static-data/na/v1.2/champion/" +id +"/?api_key=....."
xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", champUrl, false );
xmlHttp.send( null );
var jsonText = xmlHttp.responseText;
var champData = JSON.parse(jsonText);
var champName = champData.key;
return getChampionImage["_"+id]="http://ddragon.leagueoflegends.com/cdn/" + versionNum + "/img/champion/"+champName+".png";
}
EDIT: to persist the url data between page visits, use localStorage as the hash object:
function getChampionImage(id) {
var cached=localStorage["_"+id];
if(cached) return cached;
var champUrl = "https://na.api.pvp.net/api/lol/static-data/na/v1.2/champion/" +id +"/?api_key=....."
xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", champUrl, false );
xmlHttp.send( null );
var jsonText = xmlHttp.responseText;
var champData = JSON.parse(jsonText);
var champName = champData.key;
return localStorage["_"+id]="http://ddragon.leagueoflegends.com/cdn/" + versionNum + "/img/champion/"+champName+".png";
}
note that with localStorage, you'll have to self-expire the cache if you make changes.

Setting server response data to a variable to work with

Hey guys I am using a executePostHttpRequest function that looks exactly like the code posted below. Currently when I run the function I get a server response with the appropriate data but I am not sure how I can work with the response data? how do I store it in to a variable to work with?
Javascript executePostHttpRequest
function executePostHttpRequest(url, toSend, async) {
console.log("====== POST request content ======");
console.log(toSend);
var xmlhttp = new XMLHttpRequest(); // new HttpRequest instance
xmlhttp.open("POST", url, async);
xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xmlhttp.setRequestHeader("Content-length", toSend.length);
xmlhttp.send(toSend);
console.log("====== Sent POST request ======");
}
Here is what I am doing to execute it. Using Javascript
var searchCriteria = JSON.stringify({
displayName : search_term
});
console.log("Search: "+searchCriteria) //Search: {"name":"John, Doe"}
var response = executePostHttpRequest("/web/search", searchCriteria, true);
console.log(response) //undefined
So currently the console.log for response shows undefined. But if I take a look at the network tab on Chrome Dev Tools and look at the /web/search call I see a JSON string that came back that looks something like this.
[{"id":"1","email":"john.doe#dm.com","name":"John, Doe"}]
I'd like to be able to display the data from this response to a HTML page by doing something like this.
$("#id").html(response.id);
$("#name").html(response.name);
$("#email").html(response.email);
I tried taking another route and using Jquery POST instead by doing something like this.
var searchCriteria = JSON.stringify({
displayName : search_term
});
console.log("Search: "+searchCriteria) //Search: {"name":"John, Doe"}
$.post("/web/search", {
sendValue : searchCriteria
}, function(data) {
$.each(data, function(i, d) {
console.log(d.name);
});
}, 'json').error(function() {
alert("There was an error searching users! Please contact administrator.");
});
But for some reason when this runs I get the "There was an error" with no response from the server.
Could someone assist me with this? Thank you for taking your time to read it.
Your executePostHttpRequest function doesn't do anything with the data it's receiving. You would have to add an event listener to the XMLHttpRequest to get it:
function getPostData(url, toSend, async, method) {
// Create new request
var xhr = new XMLHttpRequest()
// Set parameters
xhr.open('POST', url, async)
// Add event listener
xhr.onreadystatechange = function () {
// Check if finished
if (xhr.readyState == 4 && xhr.status == 200) {
// Do something with data
method(xhr.responseText);
}
}
}
I've added the method parameter for you to add a function as parameter.
Here's an example of what you were trying to do:
function displayStuff(jsonString) {
// Parse JSON string
var data = JSON.parse(jsonString)
// Loop over data
for (var i = 0; i < data.length; i++) {
// Get element
var element = data[i]
// Do something with its attributes
console.log(element.id)
console.log(element.name)
}
}
getPostData('/web/search', searchCriteria, true, displayStuff)

Categories