Cannot Control if JSON is Undefined in javascript - javascript

I'm trying to create a site in which, through the Spotify Web API, I display the information of a certain element (Artist, Track, Album, etc ...).
I was trying to make a check on the url of the profile image of the Artist object as it is not said to be present, but when the console runs it gives me the error "Unexpected token }".
Could someone help me on why?
Below I leave the code:
function ricercaArtista() {
var xhr = new XMLHttpRequest();
var token = document.getElementById("token").innerHTML;
var artist = document.getElementById("artista").value;
artist = artist.replace(" ", "%20");
console.log(artist);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var response = JSON.parse(xhr.responseText);
var result = '';
for (var i = 0; i < response.artists.items.length; i++) {
console.log(response.artists.items[i]);
try { //from here start the control on the image
result += '<div class="panel panel-primary style="background:url(' +
response.tracks.items[i].album.images[1].url + '");"><div class="panel-body">' +
} catch (error) {
result += '<div class="panel panel-primary");"><div class="panel-body">' +
}
'name : ' + response.artists.items[i].name + '<br/>' +
'popularity : ' + response.artists.items[i].popularity + '<br/>' +
'type : ' + response.artists.items[i].type + '<br/>' +
'' + 'Apri su Spotify' + '<br></div></div>';
}
alert
document.getElementById("artists").innerHTML = result;
}
};
xhr.open('GET', "https://api.spotify.com/v1/search?q=" + artist + "&type=artist", true);
xhr.setRequestHeader('Accept', 'application/json');
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.setRequestHeader('Authorization', 'Bearer ' + token);
xhr.send();
}

Related

Uncaught ReferenceError (variable is defined and show in console,but show me this error)

I wrote the following code and the ciso variable is defined and its value is displayed when the code is executed, but when the find_cites function is executed, it shows the Uncaught ReferenceError: x is not defined error.
function find_states(ciso){
var request = new XMLHttpRequest();
request.open('GET', 'https://api.countrystatecity.in/v1/countries/' + ciso + '/states');
request.setRequestHeader('xx', 'xx');
request.onreadystatechange = function () {
if (this.readyState === 4) {
// console.log('Status:', this.status);
// console.log('Headers:', this.getAllResponseHeaders());
// console.log('Body:', this.responseText);
var items2 = JSON.parse(request.responseText);
var output2 = "<select name='state' class='form-select' aria-label='Default select example' style='width: 50%;margin-right: 5%;'>";
// document.getElementById("test").innerHTML = items2;
for(var key in items2){
console.log(items2[key]);
output2+='<option onclick="find_cites(' + ciso + ',' + items2[key].iso2 + ')">' + items2[key].name + '</option>';
}
output2+="</select>";
document.getElementById("state").innerHTML = output2;
// console.log(ciso);
}
};
request.send();
};
function find_cites(ciso,siso){
var request = new XMLHttpRequest();
equest.open('GET', 'https://api.countrystatecity.in/v1/countries/' + ciso + '/states/' + siso + '/cities');
request.setRequestHeader('xx', 'xx');
request.onreadystatechange = function () {
if (this.readyState === 4) {
// console.log('Status:', this.status);
// console.log('Headers:', this.getAllResponseHeaders());
// console.log('Body:', this.responseText);
var items2 = JSON.parse(request.responseText);
var output2 = "<select name='city' class='form-select' aria-label='Default select example' style='width: 50%;margin-right: 5%;'>";
// document.getElementById("test").innerHTML = items2;
for(var key in items2){
console.log(items2[key]);
output2+="<option>" + items2[key].name + "</option>";
}
output2+="</select>";
document.getElementById("city").innerHTML = output2;
// console.log(ciso);
}
};
request.send();
};
You've got possible error here:
equest.open('GET', 'https://api.countrystatecity.in/v1/countries/' + ciso + '/states/' + siso + '/cities');
Should be:
request.open('GET', 'https://api.countrystatecity.in/v1/countries/' + ciso + '/states/' + siso + '/cities');
The ciso variable is a string and must be enclosed in quotation marks ('') when entering the function, but this was ignored when passing data to the function, and the error was related to this point.
The following codes are illustrative:
Old code:
output2+='<option onclick="find_cites(' + ciso + ',' + items2[key].iso2 + ')">' + items2[key].name + '</option>';
New code:
output2+='<option onclick="find_cites(' + "'" + ciso + "'" + ',' + "'" + items2[key].iso2 + "'" + ')">' + items2[key].name + '</option>';

I've got "The object's state must be OPENED."

I've tried to perform AJAX request, but I've got this kind of error, that ajax call should be opened. But it is opened already. Trying to send the XMLHttpRequest header, but getting this kinda error. Guys, help me!
let del_btn = document.querySelectorAll('.delete');
for(let i = 0; i < del_btn.length; i++)
{
del_btn[i].addEventListener('click', function(){
let xhr = new XMLHttpRequest();
let book_title = del_btn[i].parentElement.children[1].children[1].children[0].children[0].textContent;
xhr.onreadystatechange = function()
{
if(xhr.readyState == 4 && xhr.status == 200)
{
if(this.responseText.includes('Deleted'))
{
let books = this.responseText.split('.')[1];
if(books == '0')
{
del_btn[i].parentElement.parentElement.innerHTML = 'You have no books in your list. Go to the ' + ' ' + ' main page ' + ' ' + 'and start your ride!';
}
else
{
del_btn[i].parentElement.parentElement.removeChild(del_btn[i].parentElement);
document.querySelector('.amount-b').textContent = 'Количество книг: ' + books;
}
}
}
}
xhr.open("POST", "../operations/delete_book.php", true);
xml.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send('title=' + book_title);
}, false);
}```

Twitch TV API JSON Issue

I work with Twitch API. If the streamer streams I work with with property "Stream". But If he's not streaming, then I need refer to another link. Then I again turn to the function of the getJSON and pass there the necessary API link. And I'm working with her. However, the loop does not work as it should. It takes the last streamer out of the "channels" array, but it should all those who do not stream. I can not understand what the problem is. Help...
JSFiddle: https://jsfiddle.net/e7gLL25y/
JS Code:
var getJSON = function(url, callback) {
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.onload = function() {
if(xhr.readyState == 4 && xhr.status == "200") {
callback(JSON.parse(xhr.responseText));
}
};
xhr.send();
};
var channels = ["summit1g", "esl_RuHub_CSGO", "Starladder1", "Senpai_Frozen", "tehvivalazz", "ESL_CSGO"];
var client_id = "hx3dea4ifwensxffoe8iwvekwvksnx";
var section = document.getElementById("main-section");
var streamer = [];
for(var i = 0; i < channels.length; i++) {
var url_channels = "https://api.twitch.tv/kraken/channels/" + channels[i] + "?client_id=" + client_id;
var url_streams = "https://api.twitch.tv/kraken/streams/" + channels[i] + "?client_id=" + client_id;
getJSON(url_streams, function(response) {
if( response["stream"] !== null ) {
streamer[i] = document.createElement("div");
streamer[i].className = "streamer";
streamer[i].innerHTML = "<a target='_blank' href='" + response.stream.channel["url"] +
"'><img id='streamer-image' src='" +
response.stream.channel["logo"] +
"' alt='Av' /><h2 id='streamer-name'>" +
response.stream.channel["name"] +
"</h2><p id='stream-status'>" +
response.stream["game"] + "</p></a>";
section.appendChild(streamer[i]);
} else {
getJSON(url_channels, function(r) {
streamer[i] = document.createElement("div");
streamer[i].className = "streamer";
streamer[i].innerHTML = "<a target='_blank' href='" + r["url"] +
"'><img id='streamer-image' src='" +
r["logo"] +
"' alt='Av' /><h2 id='streamer-name'>" +
r["name"] +
"</h2><p id='stream-status'>Offline</p></a>";
section.appendChild(streamer[i]);
});
}
});
}
You are having a common misconception about JavaScript contexts.
Refer to my answer here to see details about this problem: https://stackoverflow.com/a/42283571/1525495
Simply, the getJSON response is called after all the array is looped, so i will be the last index in all the responses. You have to create another context to keep the i number so is not increased.
for(var i = 0; i < channels.length; i++) {
var url_channels = "https://api.twitch.tv/kraken/channels/" + channels[i] + "?client_id=" + client_id;
var url_streams = "https://api.twitch.tv/kraken/streams/" + channels[i] + "?client_id=" + client_id;
(function(i) {
// i will not be changed by the external loop as is in another context
getJSON(url_streams, function(response) {
// Thingy things...
});
})(i);
}

getting XMLHttpRequest cannot load (URL) Response for preflight is invalid (redirect)

here am trying to get reccurring events from calendar list for sharepoint Online app and there am using code as like
hostWebUrl = decodeURIComponent(manageQueryStringParameter('SPHostUrl'));
function GetListData() {
var webUrl = hostWebUrl;// = "http://server/sitewhereyourlistexists";
var listGuid = "{2000da75-8663-42d9-9999-ad855c54b4e0}"
// An XMLHttpRequest object is used to access the web service
var xhr = new XMLHttpRequest();
var url = webUrl + "/_vti_bin/Lists.asmx";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
xhr.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/sharepoint/soap/GetListItems");
// The message body consists of an XML document
// with SOAP elements corresponding to the GetListItems method parameters
// i.e. listName, query, and queryOptions
var data = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">" +
"<soap:Body>" +
"<GetListItems xmlns=\"http://schemas.microsoft.com/sharepoint/soap/\">" +
"<listName>" + listGuid + "</listName>" +
"<query>" +
"<Query><Where>" +
"<DateRangesOverlap>" +
"<FieldRef Name=\"EventDate\"/>" +
"<FieldRef Name=\"EndDate\"/>" +
"<FieldRef Name=\"RecurrenceID\"/>" +
"<Value Type=\"DateTime\"><Today/></Value>" +
"</DateRangesOverlap>" +
"</Where></Query>" +
"</query>" +
"<queryOptions>" +
"<QueryOptions>" +
"<ExpandRecurrence>TRUE</ExpandRecurrence>" +
"</QueryOptions>" +
"</queryOptions>" +
"</GetListItems>" +
"</soap:Body>" +
"</soap:Envelope>";
// Here we define what code we want to run upon successfully getting the results
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
var doc = xhr.responseXML;
// grab all the "row" elements from the XML results
var rows = doc.getElementsByTagName("z:row");
var results = "Today's Schedule (" + rows.length + "):\n\n";
var events = {};
for (var i = 0, len = rows.length; i < len; i++) {
var id = rows[i].getAttribute("ows_FSObjType"); // prevent duplicates from appearing in results
if (!events[id]) {
events[id] = true;
var allDay = rows[i].getAttribute("ows_fAllDayEvent"),
title = rows[i].getAttribute("ows_Title"),
start = rows[i].getAttribute("ows_EventDate");
var index = start.indexOf(" ");
var date = start.substring(5, index) + "-" + start.substring(2, 4); // get the date in MM-dd-yyyy format
start = start.substring(index, index + 6); // get the start time in hh:mm format
var end = rows[i].getAttribute("ows_EndDate");
index = end.indexOf(" "); end = end.substring(index, index + 6); // get the end time in hh:mm format
results += date + " " + (allDay == "1" ? "All Day\t" : start + " to " + end) + " \t " + title + "\n";
}
}
alert(results);
} else {
alert("Error " + xhr.status);
}
}
};
// Finally, we actually kick off the query
xhr.send(data);
}
after calling this function in decument. ready section it is not retrieving any data but there is ine error which i can see in console of browser that is as below
You will click on the correct request in the left hand side panel, then select "Inspectors" in the right hand side top panel. Then choose between the different request and response options.

ContextMenuItem context function is not executing

I want my context menu item to be visible only if the clicked node is a link i.e. and href is either a magnet link or a torrent link. But item is visible for all the links because context function is not executing, can anybody help why context function is not executing?
Here is the code:
exports.main = function() {
var cm = require("sdk/context-menu");
var contextCode = ' self.on("context", function (node) { '+
' while(node.nodeName!="A") { node = node.parentNode; } '+
' var pat_magnet = /^magnet:/i; ' +
' var pat_torrent = /.torrent$/i; ' +
' if(pat_torrent.test(node.href) || pat_magnet.test(node.href)) { return true; } '+
' else { return false; } '+
' }); ';
var clickCode = ' self.on("click", function(node,data){ '+
' while(node.nodeName!="A") { node = node.parentNode; } '+
' var pat_hash = /[0-9abcdef]{32,40}/i; ' +
' var result = node.href.match(pat_hash); '+
' var hash = "" '
' if(result != null) { hash=result[0]; } '+
' var xhr = new XMLHttpRequest(); '+
' if(hash != "") { '+
' var apiCall = "https://www.furk.net/api/dl/add?api_key=*************&info_hash="+hash; '+
' } '+
' else{ '+
' var apiCall = "https://www.furk.net/api/dl/add?api_key=*************&url="+encodeURI(node.href); '+
' } '+
' xhr.open("GET",apiCall,true); '+
' xhr.onreadystatechange = function(){ if(xhr.readyState = 4) { if (xhr.response.status = "ok") { alert("Torrent added to Furk."); } else { alert("Torrent could not be added to Furk."); } } } '+
' xhr.send(null); '+
' });';
cm.Item({
label: "Add to Furk",
context: cm.SelectorContext("a[href]"),
contentScript: contextCode + clickCode
});
};
Please always post self-containied examples that can be directly tried in the future.
Now back to your problem: The content script actually has a syntax error.
The following line:
' var pat_torrent = /.torrent$/i ' +
lacks a semicolon, and should be:
' var pat_torrent = /.torrent$/i; ' +
The reason automatic semicolon insertion (ASI) does not work here is: The "code" is actually a string that has no newlines in it whatsoever. If there were newlines, then ASI would have worked.
Anway, another reason not to have complex content script inline. Have a look at contentScriptFile.
This error is actually logged, but the presentation sucks. In the Browser Console:
[20:57:51.707] [object Error] (expandable)
In terminal:
console.error: context-magnet:
Message: SyntaxError: missing ; before statement
Here is a fixed, reproducible sample:
var cm = require("sdk/context-menu");
var contextCode = ' self.on("context", function (node) { '+
' while(node.nodeName!="A") { node = node.parentNode; } '+
' var pat_magnet = /^magnet:/i; ' +
' var pat_torrent = /.torrent$/i; ' +
' if(pat_torrent.test(node.href) || pat_magnet.test(node.href)) { return true; } '+
' else { return false; } '+
' }); ';
cm.Item({
label: "magnet test",
context: cm.SelectorContext("a[href]"),
contentScript: contextCode
});
Edit ' var hash = "" ' has the same problem, and there are might be other such errors that I missed skimming this new code.
As I already said, please use contentScriptFile and not contentScript for long-ish scripts.
Another edit
Here is a builder using contentScriptFile, where I also fixed a couple of other errors, the most important of which are:
Use permissions so that the XHR will work.
Correctly set up the XHR to use responseType and overrideMimeType().
Use onload/onerror instead of onreadystatechange.

Categories