I am trying to insert pictures to id "pokedex-view" by using Ajax GET. I think "spriteurl" is showing the correct path. But does not work correctly, and it cannot find the pciture for the local folder. Is there something wrong in this code. Thanks.
function populatePokedex() {
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://webster.cs.washington.edu/pokedex/pokedex.php?pokedex=all");
xhr.onload = function(){
if (this.status == 200) {
var picArr = this.responseText.split("\n");
for(var i=0; i < picArr.length; i++){
var eachName = picArr[i].split(":")
var spriteurl = "/Pokedex/sprites/" + eachName[1];
document.getElementById("pokedex-view").innerHTML += spriteurl
document.getElementById("pokedex-view").innerHTML += "<img src = spriteurl>";
}
} else {
document.getElementById("pokedex-view").innerHTML = "ERROR: Status: " + this.status + ", " + this.statusText;
}
}
xhr.onerror = function(){
document.getElementById("pokedex-view").innerHTML = "ERROR";
}
xhr.send();
}
Try to concatenate or to interpolate the way you assign the spriteurl as the src attribute:
document.getElementById("pokedex-view").innerHTML += '<img src="' + spriteurl + '">'
Or:
document.getElementById("pokedex-view").innerHTML += `<img src="${spriteurl}">`
Related
I'm trying to pull thumbnail URLs from a wordpress feed and keep getting [object HTMLCollection] instead of an image URL string for the thumbnail. The feed i'm pulling from is: https://harpercollegece.com/feed/. I know that the tag is named media:thumbnail and the value is stored in 'URL'. I can't find the correct way to reference this image inside of the forEach loop when running through each post. I've tried searching other posts as well as on google for several hours.
var proxy = 'https://api.allorigins.win/raw?url=';
var feeds = [
'https://harpercollegece.com/feed/',
];
var limit = 10;
var forEach = function (array, callback, scope) {
for (var i = 0; i < array.length; i++) {
callback.call(scope, i, array[i]);
}
};
function strip_tags(string) {
if ((string === null) || (string === '')) {
return '';
} else {
string = string.toString();
}
string = string.replace('<![CDATA[', '');
string = string.replace(' […]]]>', '');
string = string.replace(/<[^>]*>/g, '');
string = string.replace(/<[^>]*>/g, '');
string = string.replace(']]>', '');
return string;
}
function get_rss(url) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState !== 4) {
return;
}
if (xhr.status >= 200 && xhr.status < 300) {
var response = xhr.responseText;
var parser = new window.DOMParser();
var data = parser.parseFromString(response, "text/xml");
var items = Array.from(data.querySelectorAll("item"));
var output = '';
forEach(items, function(index, item) {
if (index <= limit) {
var ilink = item.querySelector("link").innerHTML;
var title = item.querySelector("title").innerHTML;
var descr = item.querySelector("description").innerHTML;
var thumb = item.getElementsByTagName("media:thumbnail");
//console.log(item);
output +=
'<div class="ce-blog-slider-well">' +
'<div class = "ce-blog-thumb">' +
'<img class="blog-post-img" src="' + thumb + '" alt="Veterans Center Sign">' +
'</div>' +
'<div class = "ce-blog-header">' +
'' + strip_tags(title) + '' +
'</div>' +
'<div class ="ce-blog-descr">' + strip_tags(descr) + '</div>' +
'</div>';
}
});
var d1 = document.getElementById('wp-blog-posts');
d1.insertAdjacentHTML("beforeend", output);
}
};
xhr.open('GET', url);
xhr.send();
}
forEach(feeds, function(index, feed) {
get_rss(proxy + encodeURIComponent(feed));
});
<div class="ce-blog-slider" id="wp-blog-posts"></div>
getElementsByTagName returns an HTMLCollection. To get the URL, you'll have to grab the first element in that collection with [0]. The URL is stored in an attribute called url, a la
<media:thumbnail url="https://harpercollegece.files.wordpress.com/2021/01/writing-red-typewriter-typing.jpg" />
From your HTMLElement, get the url attribute like so:
var thumb = item.getElementsByTagName("media:thumbnail")[0].getAttribute("url");
var proxy = 'https://api.allorigins.win/raw?url=';
var feeds = [
'https://harpercollegece.com/feed/',
];
var limit = 10;
var forEach = function (array, callback, scope) {
for (var i = 0; i < array.length; i++) {
callback.call(scope, i, array[i]);
}
};
function strip_tags(string) {
if ((string === null) || (string === '')) {
return '';
} else {
string = string.toString();
}
string = string.replace('<![CDATA[', '');
string = string.replace(' […]]]>', '');
string = string.replace(/<[^>]*>/g, '');
string = string.replace(/<[^>]*>/g, '');
string = string.replace(']]>', '');
return string;
}
function get_rss(url) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState !== 4) {
return;
}
if (xhr.status >= 200 && xhr.status < 300) {
var response = xhr.responseText;
var parser = new window.DOMParser();
var data = parser.parseFromString(response, "text/xml");
var items = Array.from(data.querySelectorAll("item"));
var output = '';
forEach(items, function(index, item) {
if (index <= limit) {
var ilink = item.querySelector("link").innerHTML;
var title = item.querySelector("title").innerHTML;
var descr = item.querySelector("description").innerHTML;
var thumb = item.getElementsByTagName("media:thumbnail")[0].getAttribute("url");
//console.log(item);
output +=
'<div class="ce-blog-slider-well">' +
'<div class = "ce-blog-thumb">' +
'<img class="blog-post-img" src="' + thumb + '" alt="Veterans Center Sign">' +
'</div>' +
'<div class = "ce-blog-header">' +
'' + strip_tags(title) + '' +
'</div>' +
'<div class ="ce-blog-descr">' + strip_tags(descr) + '</div>' +
'</div>';
}
});
var d1 = document.getElementById('wp-blog-posts');
d1.insertAdjacentHTML("beforeend", output);
}
};
xhr.open('GET', url);
xhr.send();
}
forEach(feeds, function(index, feed) {
get_rss(proxy + encodeURIComponent(feed));
});
<div class="ce-blog-slider" id="wp-blog-posts"></div>
I have this issue with my XMLHttpRequest that I'm making. The idea is that the loop is mean to loop through a JSON array of users and also load their profile image. Loading the users works absolutely fine but when I loop to get the profile image, it shows it with the last user.
I can see where the issue lies but I don't know how to solve it. When I debug this, it does not run the xhr[i].onload part, which is important because I'm trying to append the image found to the id of the user as the loop runs. The first part of the loop will create the 'img id ="username"' for the username and then i want the XHR request to run and get the image and then append it to the 'img id' tag.
function parseJSON() {
console.log(jsonArrayOfUsers);
var htmlStart = '<ul class ="softwares">';
var htmlEnd = '</ul>'
var html = ''
var len = jsonArrayOfUsers.length;
for (var i = 0; i < len; i++) {
var xhr = [];
currentuser = jsonArrayOfUsers[i].username;
currentavatar = jsonArrayOfUsers[i].avatar
console.log(currentuser);
html += '<li class ="softwares">'
+ '<p><img id ="' + jsonArrayOfUsers[i].username + '" width="auto" height="100px"/></p>'
+ '<p>' + jsonArrayOfUsers[i].fullName + '</p>'
+ '<p>' + jsonArrayOfUsers[i].username + '</p>'
+ '<p>' + jsonArrayOfUsers[i].university + '</p>'
+ '<p>' + jsonArrayOfUsers[i].userType + '</p></li>';
(function (i){
if (jsonArrayOfUsers[i].avatar == null){}
else{
xhr[i] = new XMLHttpRequest();
xhr[i].open("GET", "URL TO API" + jsonArrayOfUsers[i].avatar, true);
xhr[i].setRequestHeader("Authorization", localStorage.token);
xhr[i].responseType = 'blob';
xhr[i].onload = function response(e) {
var urlCreator = window.URL || window.webkitURL;
imageUrl = urlCreator.createObjectURL(this.response);
document.querySelector("#" + currentuser).src = imageUrl;
};
xhr[i].send();
}})(i);
}
var htmlFull = htmlStart + html + htmlEnd
$('.people').append(htmlFull);
The way you are appending insecure text into html is bad...
I would have solved it this way using a simple forEach loop instead of a for loop
function parseJSON() {
var list = $('<ul class="softwares">');
var url = window.URL || window.webkitURL;
jsonArrayOfUsers.forEach(function(user) {
var currentuser = user.username;
var currentavatar = user.avatar;
console.log(currentuser);
var img = $('<img>', {
id: user.username,
width: 'auto',
height: '100px'
})[0];
$('<li class ="softwares">').append(
$('<p>').append(img),
$('<p>', {text: user.fullName}),
$('<p>', {text: user.username}),
$('<p>', {text: user.university}),
$('<p>', {text: user.userType})
).appendTo(list)
if (jsonArrayOfUsers[i].avatar == null) {
} else {
var xhr = new XMLHttpRequest();
xhr.open("GET", "URL TO API" + user.avatar);
xhr.setRequestHeader("Authorization", localStorage.token);
xhr.responseType = 'blob';
xhr.onload = function response(e) {
img.onload = function() {
url.revokeObjectURL(this.src);
}
img.src = url.createObjectURL(xhr.response);
};
xhr.send();
}
})
$('.people').append(list);
}
So in my code I created a table pulling from an XML file that displayed two columns of information about plants. The goal of my program is to be able to hover over the first and print out the other information about that plant and print it in another section to the right of my table. The issue is that I am not gettign any console errors and the hover affect is not printing any information.
window.addEventListener("load", link_events);
var xhr = false;
function link_events() {
xhr = new XMLHttpRequest();
if(xhr) {
xhr.addEventListener("readystatechange", ShowFile);
xhr.open("GET", "plants.xml", true);
xhr.send();
} else {
alert("XHR not supported.");
}
}
function ShowFile() {
var i;
var title;
var cover;
var plant_table = "<table><tr><th>Common Name </th><th>Botanical Name </th></tr>";
if (xhr.readyState == 4) {
if (xhr.status == 200) {
//here we have gotten the file correctly
//loop through it and print out cover and title
var plantlist = xhr.responseXML.getElementsByTagName("PLANT");
//booklist is an array and each element is an object sub i
//so you have to use getElementBy something in order to pull the information
for (i = 0; i < plantlist.length; i++) {
var Common = plantlist[i].getElementsByTagName("COMMON")[0].firstChild.textContent;
var Botanical = plantlist[i].getElementsByTagName("BOTANICAL")[0].firstChild.textContent;
plant_table += "<tr>" +
"<td class =\"plant\">" + Common + "</td>" +
"<td>" + Botanical + "</td>" +
"</tr>";
}
plant_table += "</table>";
document.getElementById("outarea").innerHTML = plant_table;
}
var plants = document.getElementsByClassName("plant");
for (i=0; i < plants.length; i++) {
plants[i].onmouseover = HoverChoice;
}
}
function HoverChoice() {
var input = xhr.responseXML.getElementsByTagName("PLANT");
for (i = 0; i < input.length; i++) {
Common = input[i].getElementsByTagName("COMMON")[0].firstChild.textContent;
var Zone = input[i].getElementsByTagName("ZONE")[0].firstChild.textContent;
var Light = input[i].getElementsByTagName("LIGHT")[0].firstChild.textContent;
var Price = input[i].getElementsByTagName("PRICE")[0].firstChild.textContent;
if (plants == this.innerHTML) {
document.getElementById("inarea").innerHTML =
"<h1>" + Common + "</h1>" + "<br />" + "<br />" +
"Zone: " + Zone + "<br />" +
"Light: " + Light + "<br />" +
"Price: " + Price;
}
}
}
}
you could try using addEventListener method instead and see whether it works?
plants.forEach(function(plant){
plant.addEventListener("onmouseover", HoverChoice);
});
or going with the original loop you made it would be
for (i=0; i < plants.length; i++)
{
plants[i].addEventListener("onmouseover", HoverChoice);
}
I'm not anything professional, a common problem I used to encounter in these kinds of event listening functions was that calling a global function sometimes fails but making the function on the spot inside the event listener would work like addEventListener("onmouseover" , function() { return 0; });
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);
}
I have a problem with getting the specific data based on my id.
This is my main html.
<div class="container">
<div class="row">
<div class="col-md-12">
<button id="btn">Button</button>
<br>
<div id="id01"></div>
</div>
</div>
</div>
This is my main js
var btn=document.getElementById("btn");
btn.addEventListener("click", function(){
var ourRequest = new XMLHttpRequest();
var url = "url.../incident";
contentType="applicaton/json; charset=utf-8";
method="GET";
dataType= "json";
ourRequest.onreadystatechange=function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this.responseText);
}
}
ourRequest.open("GET", url, true);
ourRequest.send();
});
function myFunction(response) {
var arr = JSON.parse(response);
var out = "<table>";
for(i = 0; i < arr.length; i++) {
out += "<tr><td>" +
arr[i].Address +
"</td><td><a href='lista.html?id="+arr[i].ID+"'>" +
arr[i].ID +
"</a></td><td>" +
arr[i].Category +
"</td></tr>";
}
out += "</table>";
document.getElementById("id01").innerHTML = out;
}
This will show me only three data.
this is my lista.html
<div class="container">
<div class="row">
<div class="col-md-12">
<div id="id02">
</div>
</div>
</div>
And this is my js for my lista.html.
var ourRequest = new XMLHttpRequest();
var url = "url../incident?id=";
contentType="applicaton/json; charset=utf-8";
method="GET";
dataType= "json";
ourRequest.onreadystatechange=function()
{
if (this.readyState == 4 && this.status == 200) {
myFunction(this.responseText);
}
}
ourRequest.open("GET", url, true);
ourRequest.send();
function myFunction(response)
{
var arr = JSON.parse(response);
var out = "<table>";
out +="<tr><td>" +
arr.Address +
"</td><td>" +
arr.CaseID +
"</td><td>" +
arr.Category +
"</td><td>" +
arr.Date +
"</td><td>" +
arr.Description +
"</td><td>" +
arr.ID +
"</td><td>" +
arr.InputDate +
"</td><td>" +
arr.Latitude +
"</td><td>" +
arr.Longitude +
"</td><td>" +
arr.ReportedBy +
"</td><td>" +
arr.Subcategory +
"</td><td>" +
arr.Time +
"</td></tr>"
out += "</table>";
document.getElementById("id02").innerHTML = out;
}
So when I click on that arr[i].ID it should send me to th lista.html with the specific ID and specific data.
For example if i click on ID=1, the url look like lista.html?id=1, but nothing shows.
Just pass the id to the request url if the api you send request to expects that
var url = "url?id={your id here}"
In your table you have to use arr.Address instead of response.Address, since the arr is the parsed json object.
You can use console.log to see if the data you need is really there:
function myFunction(response) {
var arr = JSON.parse(response);
console.log(arr);
}
You don't need to read the location href with jQuery, since you already know the id of the request you sent!
So My mistake was like this instead of :
var url = "url../incident?id=";
I should have written :
var url = "url../incident?id="+getQueryVariable("id");
And write this function in the end of my js for my lista.html
function getQueryVariable(variable)
{
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if(pair[0] == variable){return pair[1];}
}
return(false);
}