If/else statement in case JSON endpoint doesn’t exists - javascript

I am trying to create a scenario where if endpoint doesn’t exists, function still returns a value.
When the endpoint exists, I get a value, no problem.
var main = function(){
json_url = "http://ergast.com/api/f1/current/next.json";
xhr = new XMLHttpRequest();
xhr.open("GET", json_url, false);
xhr.send(null);
weather = JSON.parse(xhr.responseText);
let race = " ";
if (weather.MRData.RaceTable.Races[0].Sprint.date === undefined) {
race = " ";
}
else {
race = weather.MRData.RaceTable.Races[0].Sprint.date;
}
return race;
}
I get the following result
2022-07-09
But in case the endpoint doesn’t exists, I get a error.
var main = function(){
json_url = "http://ergast.com/api/f1/current/last.json";
xhr = new XMLHttpRequest();
xhr.open("GET", json_url, false);
xhr.send(null);
weather = JSON.parse(xhr.responseText);
let race = " ";
if (weather.MRData.RaceTable.Races[0].Sprint.date === undefined) {
race = " ";
}
else {
race = weather.MRData.RaceTable.Races[0].Sprint.date;
}
return race;
}
How can I rectify this. Do I have to assign something other than undefined in this case.

Use as below:
var main = function(){
json_url = "http://ergast.com/api/f1/current/last.json";
xhr = new XMLHttpRequest();
xhr.open("GET", json_url, false);
xhr.send(null);
weather = JSON.parse(xhr.responseText);
return weather.MRData.RaceTable.Races[0].date;
}
or:
race = weather.MRData.RaceTable.Races[0].FirstPractice.date;
or:
race = weather.MRData.RaceTable.Races[0].Qualifying.date;

Related

XML response text is undefined

I am making a call to an external server and am getting a valid response back with data. If I dump that data into console.log() I can see the data that I'm looking for. However the returned data is XML and if I try and use the getElementsByTagName method on the response text I get the error Uncaught TypeError: searchResults.getElementsByTagName is not a function. I checked and searchResults is undefined, which I'm assuming is my problem, I'm just not sure how to fix it.
function getBggData() {
var searchTerm = document.getElementById("searchTerm").value;
// console.log("Search Term = " + searchTerm);
var httpURL = "https://www.boardgamegeek.com/xmlapi2/search?type=boardgame,boardgameexpansion&query=" + searchTerm
// console.log("URL used is = " + httpURL);
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
displayData(this);
}
};
xhttp.open("GET", httpURL, true);
xhttp.send();
};
function displayData(xml) {
var i;
var searchResults = xml.responseText;
console.log(searchResults.type);
console.log(searchResults);
var table = "<tr><th>Game</th><th>Year Released</th></tr>";
var x = searchResults.getElementsByTagName("item");
document.getElementById("resultsHeader").innerHTML = "Search Results = " + x + " items.";
document.getElementById("searchResults").innerHTML = table;
};
you can do like this,
var parser = new DOMParser();
var xmlDoc = parser.parseFromString(xml,"text/xml");
console.log(xmlDoc.getElementsByTagName("title")[0]);
here we are parsing the xml and getting it to the variable xmlDoc
var searchResults = xml.responseXML;

js xml response return undifined

Please I need help !
To begin I don't speaking very well english sorry for the mistakes
So I'm tryng to receive a JSON Object with this code :
function uhttp(url){
var xhr = new XMLHttpRequest();
xhr.open('get', url, true);
xhr.responseType = 'json';
xhr.onload = function() {
var status = xhr.status;
if (status == 200) {
console.log(xhr.response)
return xhr.response;
}
};
xhr.send();
console.log('exit')
};
but when I use the function https like this :
`
( ()=>{
var perso =uhttp('bd.php?table=charac')
for (var i = 0; i < perso.lenght; i++) {
document.getElementbyID('container').append('<ul>'+perso[i].nom+'</ul>')
}
})()
`
perso he's undifined...
here the console of index.html
I've the impression that we'are exit the function before that whe receive the resonse and that is why the function return a null
Of course before to ask my question I'have make some research but no one working in my case....
Thank you for yours anwsers
It happens because you aren't returning value from uhttp() function but from anonymous function (xhr.onload).
In order to access this value after the AJAX call is over use promises:
function uhttp(url){
return new Promise(function(resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open('get', url, true);
xhr.responseType = 'json';
xhr.onload = function() {
var status = xhr.status;
if (status == 200) {
resolve(xhr.response);
return;
}
reject();
};
xhr.onerror = function() {
reject()
};
xhr.send();
})
}
And use it like so:
uhttp('bd.php?table=charac').then(function(result) {
var person = result;
for (var i = 0; i < perso.lenght; i++) {
document.getElementbyID('container').append('<ul>'+perso[i].nom+'</ul>');
}
}).catch(function() {
// Logic on error
});

Dynamically Hide Home Button in CRM 2015 using Ribbon Workbench not Working

I am creating a custom Enable Rule to hide "Import" button in my custom entity in Ribbon Workbench. Here is my JS code:
function ShowHideButton() {
var context;
var serverUrl;
var UserID;
var ODataPath;
var toReturn;
context = Xrm.Page.context;
serverUrl = context.getClientUrl();
UserID = context.getUserId();
ODataPath = serverUrl + "/XRMServices/2011/OrganizationData.svc";
var retrieveUserReq = new XMLHttpRequest();
retrieveUserReq.open("GET", ODataPath + "/SystemUserSet(guid'" + UserID + "')", true);
retrieveUserReq.setRequestHeader("Accept", "application/json");
retrieveUserReq.setRequestHeader("Content-Type", "application/json; charset=utf-8");
retrieveUserReq.onreadystatechange = function () {
toReturn = retrieveUserReqCallBack(this);
};
retrieveUserReq.send();
return toReturn;
}
function retrieveUserReqCallBack(retrieveUserReq) {
var retrievedUser = this.parent.JSON.parse(retrieveUserReq.responseText).d;
var retrievedValue = retrievedUser.BusinessUnitId;
var id = retrievedValue.Id;
var refIdAdmin;
var refIdTL;
var refMember;
refIdAdmin = "6EF4BCC3-5608-E511-9415-22000A93809E";
refIdTL = "CCFE0C41-D208-E511-9416-22000A93809E";
refMember = "1010FC5F-2D2C-E511-941A-22000AA400C9";
if (id.toUpperCase() == refIdAdmin) {
return true;
}
else if (id.toUpperCase() == refIdTL) {
return true;
}
else if (id.toUpperCase() == refMember) {
return true;
}
else {
return false;
}
}
can you please help me fix the code so that Ribbon Workbench is able to read what I want to return?
You're making async request and that is the problem your toReturn is null when the rule is validated
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);
}

Unexpected end of input error with chrome.tabs.query

I've been struggling with this and have had no luck. I've included the error and most of the context around the block in question.
var successURL = 'https://www.facebook.com/connect/login_success.html';
var userFirstName = ''
var userEmail = ''
function onFacebookLogin(){
if (localStorage.getItem('accessToken')) {
chrome.tabs.query({}, function(tabs) {
for (var i = 0; i < tabs.length; i++) {
if (tabs[i].url.indexOf(successURL) !== -1) {
var params = tabs[i].url.split('#')[1];
var accessToken = params.split('&')[0];
accessToken = accessToken.split('=')[1];
localStorage.setItem('accessToken', accessToken);
chrome.tabs.remove(tabs[i].id);
console.log(accessToken);
pullSecurityToken();
findFacebookName();
}
}
});
}
}
chrome.tabs.onUpdated.addListener(onFacebookLogin);
function pullSecurityToken(){
var pointUrl = "localhost:3000/api/v1/retrieve_token_for/" + localStorage.accessToken + "/" + localStorage.securityToken;
var xhr = new XMLHttpRequest();
xhr.open("GET", pointUrl, true);
alert(JSON.parse(xhr.responseText));
}
var response = ''
function findFacebookName(){
if (localStorage.accessToken) {
var graphUrl = "https://graph.facebook.com/me?access_token=" + localStorage.accessToken;
console.log(graphUrl);
var xhr = new XMLHttpRequest();
xhr.open("GET", graphUrl, true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if(xhr.status == '401'){
alert("Security Token Invalid, please check and try again.");
}
response = JSON.parse(xhr.responseText);
userFirstName = response.first_name
userEmail = response.email
console.log(response);
}
}
}
xhr.send();
}
Here's the error:
Error in response to tabs.query: SyntaxError: Unexpected end of input
at onFacebookLogin (chrome-extension://dapeikoncjikfbmjnpfhemaifpmmgibg/background.js:7:17)
Even if you use a synchronous request, you still need to send it. So add an xhr.send(); after the xhr.open inside pullSecurityToken.
As Felix Kling points out in the comments, the lack of send will directly cause your error, because the responseText property is still an empty string and such a string is not valid JSON whereas "" would be valid JSON.

Returning an array and storing into another array, creating a multidimensional array

EDIT: I've tried to implemented the solution, but it still doesn't work. Sorry i'm a programming idiot. Thanks for the link to the page.
In my first function databaseBOscreens i am attempting to obtain symbols of stocks according to the filter selected for a broker and/or an asset class. The function sends a request to another file which performs SELECT statement to lookup for the relevant symbols using mysqli. The result would be an array of symbols, which i then encode and subsequently parsed in this js function.
Each symbol will then go through a second process, which is my second function generatePrice() to obtain the historical prices for that particular symbol. What i'm trying to do is to loop through all symbols to generate and store the priceArr as an array in the resultArr. Sorry for being unclear.
function databaseBOscreens(broker,assetClass) {
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
var data = "broker=" + broker + "&category=" + assetClass;
xhr.open("POST", "generateSymbol.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(data);
xhr.onreadystatechange = receive_data;
function receive_data() {
if (xhr.readyState == 4 && xhr.status == 200)
{
var resultArr = JSON.parse(xhr.responseText);
var priceArr = new Array();
for(var ctr=0;ctr<resultArr.length;ctr++)
{
generatePrice(function(result,resultArr[ctr].symbol)){
priceArr[ctr] = result;
}
}
}
}
}
function generatePrice(callback,symbol) {
var xhr2;
if (window.XMLHttpRequest) {
xhr2 = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
xhr2 = new ActiveXObject("Microsoft.XMLHTTP");
}
var data2 = "symbol=" + symbol;
xhr2.open("POST", "generatePrice.php", true);
xhr2.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr2.send(data2);
xhr2.onreadystatechange = receive_data2;
function receive_data2() {
if (xhr2.readyState === 4)
{
if (xhr2.status === 200)
{
var priceArr = JSON.parse(xhr2.responseText);
callback(priceArr);
}
}
}
}
function receive_data() {
if (xhr.readyState == 4 && xhr.status == 200)
{
var resultArr = JSON.parse(xhr.responseText);
var priceArray = new Array();
for(var ctr=0;ctr<resultArr.length;ctr++)
{
priceArray = generatePrice(resultArr[ctr].symbol);
}
alert(priceArray.length);
}
}
My function generatePrice() returns an array, but i can't seem to store it in another array to create a multidimensional array. I've search everywhere i can't seem to get it work. Thanks in advance for any help rendered
generatePrice function:
function generatePrice(symbol) {
var xhr2;
if (window.XMLHttpRequest) {
xhr2 = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xhr2 = new ActiveXObject("Microsoft.XMLHTTP");
}
var data2 = "symbol=" + symbol;
xhr2.open("POST", "generatePrice.php", true);
xhr2.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr2.send(data2);
xhr2.onreadystatechange = receive_data2;
function receive_data2() {
if (xhr2.readyState == 4 && xhr2.status == 200)
{
var priceArr = JSON.parse(xhr2.responseText);
return priceArr;
}
}
}
My function generatePrice() returns an array,
No it doesn't, it returns undefined. XHR is asynchronous, see How do I return the response from an asynchronous call?.
priceArray = generatePrice(resultArr[ctr].symbol);
I can't seem to store it in another array
You didn't attempt to do so, you just stored the result of every call in the priceArray variable - instead of in a property of the array. Use
priceArray[ctr] = generatePrice(resultArr[ctr].symbol);
// or
priceArray.push( generatePrice(resultArr[ctr].symbol) );

Categories

Resources