Im totaly new in Javascript so help me figure out
I have simple Rest with data:
[
{
"id": 1,
"content": "Hello Tweet"
}
]
Im trying to get this info in my <script>
<script>
const tweetsElement = document.getElementById('tweets')
const xhr = new XMLHttpRequest();
const method = 'GET'
const url = '/tweets'
const responseType ='json'
xhr.responseType = responseType
xhr.open(method,url)
xhr.onload = function(){
const serverResponse = xhr.response
const listedItems = serverResponse.response
console.log(listedItems)
var finalTweetStr = ""
var i;
for(i=0;i<listedItems.length;i++){
console.log(i)
console.log(listedItems[i])
var currentItem = "<div class='mb-4'><h1>"+listedItems[i].id + "</h1>"+"<p>"+ listedItems[i].content+"</p></div>"
finalTweetStr += currentItem
}
tweetsElement.innerHTML = finalTweetStr;
}
xhr.send();
</script>
But it doesnt work , where is the problem?
Your main issue appears to be here:
const serverResponse = xhr.response
const listedItems = serverResponse.response
Change it to:
const listedItems = xhr.response
and you can remove the redundant serverResponse variable.
Related
I am running into a problem of when the user clicks on either the toronto or sudbury button it will only display one city weather temperature, conditions, and sunset information. This occurs because the page loads only one using one city API, i was wondering how i can call mutliple cities on openweather API using xhr
Below is the code i have tried to use to display the toronto weather and sudbury weather after the button click.
window.onload = function () {
let our_location = document.getElementById("location");
let our_temperature = document.getElementById("temperature");
let our_conditions = document.getElementById("conditions");
let our_sunset = document.getElementById("sunset");
let myAPIKey = "6b50d1fca9d05c7084f78a07d8fabaee";
let url =
"https://api.openweathermap.org/data/2.5/weather?q=Toronto,Sudbury&appid=" +
myAPIKey +
"&units=metric";
let xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
const data = xhr.response;
console.log(xhr);
let torontoBtn = document.getElementById("Toronto");
let sudburyBtn = document.getElementById("Sudbury")
function torontoButton() {
our_location.innerHTML = data.name;
our_temperature.innerHTML = data.main.temp;
our_conditions.innerHTML = data.weather[0].description;
our_sunset.innerHTML = data.sys.sunset;
output.style.display = "block";
}
torontoBtn.onclick = torontoButton;
function sudburyButton() {
our_location.innerHTML = data.name;
our_temperature.innerHTML = data.main.temp;
our_conditions.innerHTML = data.weather[0].description;
our_sunset.innerHTML = data.sys.sunset;
output.style.display = "block";
}
sudburyBtn.onclick = sudburyButton;
}
}
};
let output = document.getElementById("output");
xhr.open('GET', url);
xhr.responseType = "json";
xhr.send(null);
};
I am new to web development, and I am using a XMLHttpRequest() in JavaScript to get data from an api. I am trying to create variables from the data but am getting an error when I try to do the following. Does anyone know what is wrong with the line var data1 = data["data1"];?
<script>
const Http = new XMLHttpRequest();
const url = "www.mytestapi.com/response.json";
Http.open("GET", url);
Http.send();
Http.onreadystatechange = (e) => {
var json = JSON.parse(Http.responseText)
var data = json.Data
var data1 = data["data1"]; //issue caused here
}
<script>
you don't need to parse response data, data is parsed already , try this
const xhr = new XMLHttpRequest();
const url = "www.mytestapi.com/response.json";
xhr.open('GET', url);
xhr.responseType = 'json';
xhr.onload = () => {
console.log("load - "+ JSON.stringify(xhr.response));
var data = xhr.response;
var data1 = data["data1"]
}
xhr.onerror = () => {
console.log("error status - " + xhr.status);
}
xhr.send()
enter image description hereThe problem is that the objects of the API are not being rendered in HTML, what did I do wrong?
<button onclick = "showCountries()">Show Countries</button>
<div id = "feed"></div>
<script>
function showCountries(){
let xhr = new XMLHttpRequest()
xhr.open('GET', 'https://restcountries.com/v3.1/all', true)
xhr.onload = function(){
if(xhr.status == 200){
console.log('success')
let countries = JSON.parse(this.response)
countries.forEach(country=>{
const countryCard = document.createElement('div')
const countryCardImage = document.createElement('img')
countryCard.innerHTML = country.name
countryCardImage.src = country.flag
document.getElementById('feed').appendChild(countryCard)
})
}
}
xhr.send()
}
</script>
Because country.name is an object.You should use an string to set the innerHTML of element.
According to your response data structure, you can use it like this:
function showCountries() {
let xhr = new XMLHttpRequest()
xhr.open('GET', 'https://restcountries.com/v3.1/all', true)
xhr.onload = function() {
if (xhr.status == 200) {
console.log('success')
let countries = JSON.parse(this.response)
countries.forEach(country => {
const countryCard = document.createElement('div')
const countryCardImage = document.createElement('img')
countryCard.innerHTML = country.name.common
countryCardImage.src = country.flags.png
countryCardImage.style.width = "30px"
countryCard.append(countryCardImage)
document.getElementById('feed').appendChild(countryCard)
})
}
}
xhr.send()
}
<button onclick="showCountries()">Show Countries</button>
<div id="feed"></div>
I finally figured out how to display flags, here is the source:
function showCountries(){
let xhr = new XMLHttpRequest()
xhr.open('GET', 'https://restcountries.com/v3.1/all', true)
xhr.onload = function(){
if(xhr.status == 200){
console.log('success')
let countries = JSON.parse(this.response)
countries.forEach(country=>{
const countryCard = document.createElement('div')
const countryCardImage = document.createElement('div')// must be div to display small image
countryCard.innerHTML = country.name.common
countryCardImage.innerHTML = country.flag
console.log(country.flag)
document.getElementById('feed').appendChild(countryCard)
document.getElementById('feed').appendChild(countryCardImage) //this is it!
})
}
}
My apologies as I am very new to javascript and inexperienced so my code is very rudimentary, and I'll do the best I can at explaining myself.
I'm making a call to an API to get a blob which I then convert to base64. I can then pass this base64 string to a seperate script within the .map array - so this makes multiple calls to my script. But what I want to do is to concatenate the base64 strings into one string and pass a single call the my script.
I understand that this is asynchronous and I probably need some callbacks but im unsure how to do this in my case. Essentially I would like to make the 'base64data_1' variable within the reader.onloadend function available outside of the .map array, but the reader.onloadend function is the last action performed.
function getPhoto() {
const root = 'https://public-api.konectech.com/PROD/api/';
var acc = document.getElementById("accID").value;
var photoId1 = document.getElementById("photoID1").value;
var photoId2 = document.getElementById("photoID2").value;
var photoId3 = document.getElementById("photoID3").value;
var root1 = (root + acc + "/attachment/id/overlay/")
let uri = [root1 + photoId1,root1 + photoId2,root1 + photoId3];
let filenames = [photoId1,photoId2,photoId3];
var base64Array = [];
let base64 = uri.map (function (url) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.setRequestHeader("accept", "image/jpg");
xhr.setRequestHeader("content-type", "application/json");
xhr.setRequestHeader("x-api-key", "xxxxxxxx");
xhr.responseType = "blob";
xhr.send();
xhr.onload = function (data, filename, mime) {
var filename = (url.slice(url.lastIndexOf('/') + 1) );
const blob = new Blob([this.response], {type: mime || 'application/octet-stream'});
var reader = new FileReader();
reader.readAsDataURL(blob);
reader.onloadend = function() {
var base64data = reader.result;
const base64data_1 = (base64data.slice(base64data.lastIndexOf(',') + 1) );
//console.log([base64data_1]);
base64Array = base64data_1;
console.log([base64Array]);
return [base64Array];
};
}
});
//console.log([base64Array]);
}
I was hoping that if i could get access pass the 'base64data_1' variable as an array I could then use promise.all and .join get the desired result similar to below:
function getPhoto() {
var array =['test_1','test_2','test_3','test_4','test_5'];
var items = [];
let newArray = array.map (function (array_1) {
items = array_1 + '_appended';
console.log(items);
return [items];
})
console.log(newArray);
Promise.all(newArray)
.then( function (arrayOfValues) {
console.log(arrayOfValues.join(",")); // returns test_1_appended,test_2_appended,test_3_appended,test_4_appended,test_5_appended
})
}
I would like to get an array with objects from json using XMLHttpRequest() and assign it to a variable.
If i log it in a console it shows the array.
function getData() {
let myJson = [];
var xhr = new XMLHttpRequest();
var url = 'https://www.reddit.com/r/funny.json';
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var jsonData = JSON.parse(xhr.responseText);
arr = jsonData.data.children;
for (let i = 0; i < arr.length; i++) {
let newObject = {};
newObject.title = arr[i].data.title;
newObject.upvotes = arr[i].data.ups;
newObject.score = arr[i].data.score;
newObject.num_comments = arr[i].data.num_comments;
newObject.created = arr[i].created_utc;
myJson.push(newObject);
}
}
};
xhr.open("GET", url, true);
xhr.send();
return myJson;
}
let data = getData();
console.log(data[0]);
But if I try to do anything with (console.log(data[0]);) it it returns undefined. What am I doing wrong? Thanks for any explanation! Cheers.
Just pass in the callback function instead of returning the value from an asynchronous XML HTTP request.
function getData(callback) {
var xhr = new XMLHttpRequest();
var url = 'https://www.reddit.com/r/funny.json';
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
var jsonData = JSON.parse(xhr.responseText);
arr = jsonData.data.children;
let myJson = [];
for (let i = 0; i < arr.length; i++) {
let newObject = {};
newObject.title = arr[i].data.title;
newObject.upvotes = arr[i].data.ups;
newObject.score = arr[i].data.score;
newObject.num_comments = arr[i].data.num_comments;
newObject.created = arr[i].created_utc;
myJson.push(newObject);
}
// Invoke the callback now with your recieved JSON object
callback(myJson);
}
};
xhr.open("GET", url, true);
xhr.send();
}
getData(console.log);
Your return happens outside of the onreadystatechange. So you exit before you even have the data.
Pass in a callback function to call when you have the data, or have the asynchronous call return a JS Promise that resolves with the gotten data.