How to split the content of xmlhttp.response in javascript - javascript

i did manage to build a code that works and it does the splitting when added manually:
var input = '10;11;15;16';
var arr = input.split(';');
// update the content of the div with ID "humid"
document.getElementById('humid').textContent = arr[0];
document.getElementById('humid').style.width = `${arr[0]}%`;
document.getElementById('temp').textContent = arr[1];
document.getElementById('temp').style.width = `${arr[1]}%`;
document.getElementById('uv').textContent = arr[2];
document.getElementById('uv').style.width = `${arr[2]}%`;
document.getElementById('info').textContent = arr[3];
document.getElementById('info').style.width = `${arr[3]}%`;
the problem i have is that i want to use the data from this XMLHttpRequest,
this is how i get my value:
function readForestall() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("ForestAll").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "readFORESTALL", false);
xhttp.send();
}
setInterval(function() {
readForestall();
}, 5000);
i did try a lot of things with no result, like this:
var input = 'ForestAll';
or input = document.getElementById('ForestAll').value
regards

Related

Replace object1 values with values of object2

var object1 = {
lol_gif: [22390036, 15154597, 13491369],
silly_gif: [19048808, 19048861]
}
var ids = Object.values(object1).toString();//will return 22390036,15154597,13491369,19048808,19048861
httpGetAsync('https://g.tenor.com/v1/gifs?ids=' + ids + '&key=LIVDSRZULELA&media_filter=tinygif');
function httpGetAsync(theUrl) {
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
var response = JSON.parse(xmlHttp.responseText);
var gifs = response.results;
var object2 = {};
for (var g in gifs) {
var id = gifs[g].id;
object2[id] = gifs[g].media[0].tinygif.url;
}
console.log(object2);
//will return an object with the ID as the keys and gif url as the values
}
}
xmlHttp.open("GET", theUrl, true);
xmlHttp.send();
return;
}
I am trying to categorize each gif by replacing object1 values with data from tenor json but failed many times. thanks for your help!
desired output:
var object1 = {
lol_gif: ["https://media.tenor.com/images/4ad4bc701f2744ddc5220f6d3688e899/tenor.gif",
"https://media.tenor.com/images/c9b8564d6acbbba994b5413479d0fc2b/tenor.gif",
"https://media.tenor.com/images/7c27bea2fb5ea0f7600af7e9ad8d0c4a/tenor.gif"],
silly_gif: ["https://media.tenor.com/images/59669ec95913ef1df85fee2cda08aece/tenor.gif",
"https://media.tenor.com/images/59669ec95913ef1df85fee2cda08aece/tenor.gif"]
}
Something like this would give you an object in the same shape as your original:
var object1 = {
lol_gif: [22390036, 15154597, 13491369],
silly_gif: [19048808, 19048861]
}
var ids = Object.values(object1).toString();//will return 22390036,15154597,13491369,19048808,19048861
httpGetAsync('https://g.tenor.com/v1/gifs?ids=' + ids + '&key=LIVDSRZULELA&media_filter=tinygif');
function httpGetAsync(theUrl) {
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
var response = JSON.parse(xmlHttp.responseText);
var gifs = response.results;
var object2 = {};
Object.entries(object1).forEach(([key, gifIds]) => {
const newGifList = gifIds.map((gifId) => {
const gif = gifs.find((gifResult) => gifResult.id === gifId.toString());
return gif.media[0].tinygif.url;
});
object2[key] = newGifList;
});
console.log(object2);
//will return an object with the ID as the keys and gif url as the values
}
}
xmlHttp.open("GET", theUrl, true);
xmlHttp.send();
return;
}
Side note, its generally not a great idea to include API keys in StackOverflow questions.
I haven't really taken a deep dive into the type of responses this API provides back, but my surface-level conclusion is that if you want to maintain the exact structure and order of the data, you'll have to go with this solution:
const object = {
lolGifs: [22390036, 15154597, 13491369],
sillyGifs: [19048808, 19048861],
};
const getGifs = async (obj) => {
const map = {};
for (const [key, arr] of Object.entries(obj)) {
map[key] = [];
for (const id of arr) {
const res = await fetch(`https://g.tenor.com/v1/gifs?ids=${id}&key=LIVDSRZULELA&media_filter=tinygif`);
const { results } = await res.json();
const gifUrl = results[0]?.media[0]?.tinygif?.url;
map[key].push(gifUrl);
}
}
return map;
};
(async () => {
const data = await getGifs(object);
console.log(data);
})();
You just need to make some simple change where you search for the ids to put it to the keyname as following:
var object1 = {
lol_gif: [22390036, 15154597, 13491369],
silly_gif: [19048808, 19048861]
}
var ids = Object.values(object1).toString();//will return 22390036,15154597,13491369,19048808,19048861
httpGetAsync('https://g.tenor.com/v1/gifs?ids=' + ids + '&key=LIVDSRZULELA&media_filter=tinygif');
function httpGetAsync(theUrl) {
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
var response = JSON.parse(xmlHttp.responseText);
var gifs = response.results;
var object2 = {"lol_gif":[],"silly_gif":[]};
for (var g in gifs) {
var id = gifs[g].id;
if(object1["lol_gif"].indexOf(parseInt(id))!=-1) {
object2["lol_gif"].push(gifs[g].media[0].tinygif.url);
}
else if(object1["silly_gif"].indexOf(parseInt(id))!=-1){
object2["silly_gif"].push(gifs[g].media[0].tinygif.url);
}
}
console.log(object2);
//will return an object with the ID as the keys and gif url as the values
}
}
xmlHttp.open("GET", theUrl, true);
xmlHttp.send();
return;
}

Because I only see the last element of the for loop

I'm having a problem; I have the following program code:
var xmlhttp = new XMLHttpRequest();
var url = "https://wjko5k6250.execute-api.us-east-2.amazonaws.com/motorcycle";
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var allmot = JSON.parse(this.responseText);
console.log(allmot);
for(var i = 0, len = allmot.Items.length; i < len; i++)
{
id=allmot.Items[i].id
var url1 = "https://wjko5k6250.execute-api.us-east-2.amazonaws.com/motorcycle/"+id;
console.log(url1);
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myArr = JSON.parse(this.responseText);
console.log(myArr);
document.getElementById("img").src = myArr.Item.image;
document.getElementById("brd").innerHTML = myArr.Item.brand;
}
};
xmlhttp.open("GET", url1, true);
xmlhttp.send();
}
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
allmot is as follows:
Items: Array (4)
0: {brand: 'Guzzi', id: '123456', image: 'moto_guzzi.jpg', date: '27/11/2021 '}
1: {brand: 'Bimota', id: '135623', image: 'bimota.jpg', date: '04/12/2021 '}
2: {brand: 'Ducati', id: '123789', image: 'b_desertx.jpg', date: ' 04/12/2021 '}
3: {brand: 'Benelli', id:' 146975 ', image:' benelli.jpg ', date: '27/11/2021'}
url1 returns (according to the for loop):
https://wjko5k6250.execute-api.us-east-2.amazonaws.com/articles/123456
https://wjko5k6250.execute-api.us-east-2.amazonaws.com/articles/135623
https://wjko5k6250.execute-api.us-east-2.amazonaws.com/articles/123789
https://wjko5k6250.execute-api.us-east-2.amazonaws.com/articles/146975
and so far everything seems to be fine.
The problem is in myArr; I noticed that it returns the image and brand of the last element only, so the one that has id equal to 146975.
Therefore there seems to be problems with the for loop.
Can anyone kindly help me? Thank you all.
As first correction I'd not recycle the XHR object from the outer loop in the inner loop.
When you say xmlhttp.onreadystatechange = function() ... in the inner loop, the xmlhttp is already in the readystate, obtained in the outer loop.
So, without further checking what is going on, I'd use two XHR objects (maybe like outerXmlhttp and innerXmlhttp). I'd also recreate the inner XHR for every cycle with:
var innerXmlhttp;
at the top of the outer closure.
Then, inside the cycle do:
innerXmlhttp = new XMLHttpRequest();
This is because of variable hoisting. If you just do this:
var innerXmlhttp = new XMLHttpRequest();
inside the cycle you may get a different behaviour. Just don't do it and write what you mean (hoist variables and assign them where you actually need it).
If all of this isn't enough ask a new, more precise question about what is going on.
This is your code with the corrections:
var outerXmlhttp = new XMLHttpRequest();
var url = "https://wjko5k6250.execute-api.us-east-2.amazonaws.com/motorcycle";
outerXmlhttp.onreadystatechange = function() {
var innerXmlhttp;
if (this.readyState == 4 && this.status == 200) {
var allmot = JSON.parse(this.responseText);
console.log(allmot);
for(var i = 0, len = allmot.Items.length; i < len; i++)
{
id=allmot.Items[i].id
var url1 = "https://wjko5k6250.execute-api.us-east-2.amazonaws.com/motorcycle/"+id;
console.log(url1);
innerXmlhttp = new XMLHttpRequest();
innerXmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myArr = JSON.parse(this.responseText);
console.log(myArr);
document.getElementById("img").src = myArr.Item.image;
document.getElementById("brd").innerHTML = myArr.Item.brand;
}
};
innerXmlhttp.open("GET", url1, true);
innerXmlhttp.send();
}
}
};
outerXmlhttp.open("GET", url, true);
outerXmlhttp.send();
EDIT: #Teemu's eagle eye
As #Teemu points out in his comment, if you reassign values over and over to the same DOM objects like this:
document.getElementById("img").src = myArr.Item.image;
document.getElementById("brd").innerHTML = myArr.Item.brand;
you're clearly overwriting whatever value was there before. Instead, you should create and append those DOM objects, more like this:
var img = document.createElement("img");
img.src = myArr.Item.image;
var brd = document.createElement("p");
brd.innerText = myArr.Item.brand;
document.getElementById("motlist").append(img);
document.getElementById("motlist").append(brd);
Obviously, you'll need a <div id="motlist"></div> element or some other parent in the DOM to which to append the new elements.
For paging you may also want to clear those elements in the list... but here we're going overboard.

How do I convert this code block into a Javascript loop?

This function operates perfectly, onclick it subtracts a price amount from 7 ‘cosT’ divs and 1 ‘cosT1’ div, as if removing an item from a shopping cart.
function changePrice0000() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var x = document.querySelectorAll(".cosT, .cosT1");
x[0].innerHTML = parseFloat(Number(x[0].innerHTML) - Number(x[7].innerHTML)).toFixed(2);
x[1].innerHTML = parseFloat(Number(x[1].innerHTML) - Number(x[7].innerHTML)).toFixed(2);
x[2].innerHTML = parseFloat(Number(x[2].innerHTML) - Number(x[7].innerHTML)).toFixed(2);
x[3].innerHTML = parseFloat(Number(x[3].innerHTML) - Number(x[7].innerHTML)).toFixed(2);
x[4].innerHTML = parseFloat(Number(x[4].innerHTML) - Number(x[7].innerHTML)).toFixed(2);
x[5].innerHTML = parseFloat(Number(x[5].innerHTML) - Number(x[7].innerHTML)).toFixed(2);
x[6].innerHTML = parseFloat(Number(x[6].innerHTML) - Number(x[7].innerHTML)).toFixed(2);
x[7].innerHTML = parseFloat(Number(x[7].innerHTML) - Number(x[7].innerHTML)).toFixed(2);
}
};
xhttp.open("GET", "text/p0000.txt", true);
xhttp.send();
}
I’ve tried a few variations of the following, nooby attempts at looping and getting it to work but without even remote success…
function changePrice0000() {
for(i=0; i<7; i++) {
var xhttp = new XMLHttpRequest();xhttp.onreadystatechange = function() {if (this.readyState == 4 && this.status == 200) {
var x = document.querySelectorAll(".cosT, .cosT1");
x[n].innerHTML = parseFloat(Number(x[n].innerHTML) - Number(x[7].innerHTML)).toFixed(2);
x[0].innerHTML = parseFloat(Number(x[0].innerHTML) - Number(x[7].innerHTML)).toFixed(2);}};
xhttp.open("GET", "text/p0000.txt", true);
xhttp.send();
}
}
…way beyond my capabilities , one for the experts I think, explicit assistance or just a point in the right direction would be most gratefully appreciated.
You were close, you only need the for loop around the part of the code you want to repeat. You also used an undefined variable n instead of the i in the loop, as #Rup mentioned in the comments:
function changePrice0000() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var x = document.querySelectorAll(".cosT, .cosT1");
for(i = 0; i<7; i++) {
x[i].innerHTML = parseFloat(Number(x[i].innerHTML) - Number(x[7].innerHTML)).toFixed(2);
}
xhttp.open("GET", "text/p0000.txt", true);
xhttp.send();
}
}
}
Here a small snippet with a simple loop solution:
var x = document.querySelectorAll(".cost");
x.forEach(function(el) {
el.innerHTML = parseFloat(Number(el.innerHTML) - Number(x[7].innerHTML)).toFixed(2);
});
<div class="cost">1</div>
<div class="cost">2</div>
<div class="cost">3</div>
<div class="cost">4</div>
<div class="cost">5</div>
<div class="cost">6</div>
<div class="cost">7</div>
<div class="cost">8</div>
function changePrice0000() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var x = document.querySelectorAll(".cosT, .cosT1");
// loop over n starts here
for (n = 0; n < 7; n++) {
x[n].innerHTML = parseFloat(
Number(x[n].innerHTML) - Number(x[7].innerHTML)
).toFixed(2);
}
// loop ends here
}
xhttp.open("GET", "text/p0000.txt", true);
xhttp.send();
};
}
maybe this is what you mean? N is the var, so I from your example will not work, and you gotta makes sure your loop is inside of where you want to handle it...
Ok so huge thank you to the blisteringly fast expert responses, bit of jigging about–here is what is working perfectly (don’t ask me how :), endeavoured to indent a bit:
function changePrice0000() {var xhttp = new XMLHttpRequest();xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var x = document.querySelectorAll(".cosT, .cosT1");
// loop begins
for(n=0; n<7; n++) {
x[n].innerHTML = parseFloat(Number(x[n].innerHTML) - Number(x[7].innerHTML)).toFixed(2)};
// loop ends
x[n].innerHTML = parseFloat(Number(x[n].innerHTML) - Number(x[7].innerHTML)).toFixed(2);}};
xhttp.open("GET", "text/p0000.txt", true);
xhttp.send();}
Thanks again guys !!!
You just have to put for loop to the code which you want to repeat.
var n=7
for(i = 0; i <= n; i++) {
x[i].innerHTML = parseFloat(Number(x[i].innerHTML)-(Number(x[n].innerHTML)).toFixed(2);
}

How to add class to element if inner value changes on ajax request?

I want to write a piece of code which requests some cryptocurrency prices by ajax, it will request a FIAT currency price as well.
So, I want to add "increased" class when the price goes up & "decreased" class when the price goes down. The script runs every 3 seconds to check the new prices.
I've tried to define a variable on the innerHTML of the price element, and an if/else on what should the script do when the price changes. Here is a sample code:
var btn = document.querySelector("#refreshprice");
var price = document.querySelector("#price-text");
var btcirr = document.querySelector("#btcirrrealtime");
var currency_symbol = document.querySelector("#currency-symbol");
var usdirrinner = usdirr.innerHTML;
var priceinner = price.innerHTML;
window.onload = function(){
var USDIRR = getUSDIRRRequest();
USDIRR.send();
var XHR = getXHRRequest();
XHR.send();
var BTCIRR = realtimeirr();
};
setInterval(function(){
var USDIRR = getUSDIRRRequest();
USDIRR.send();
var XHR = getXHRRequest();
XHR.send();
var BTCIRR = realtimeirr();
},3000);
function getUSDIRRRequest(){
var USDIRR = new XMLHttpRequest();
USDIRR.open("GET","http://call2.tgju.org/ajax.json");
USDIRR.onreadystatechange = function(){
if(USDIRR.readyState == 4 && USDIRR.status == 200){
var parsedData = JSON.parse(USDIRR.responseText);
dollarrealtimeprice = parsedData.current.price_dollar_realtime.p.replace(",", "");
var dollarrealtimepricetoman = dollarrealtimeprice/10;
usdirr.innerHTML = dollarrealtimepricetoman;
if(usdirrinner >= dollarrealtimepricetoman){
usdirr.classList.add("increased");
}
else {
usdirr.classList.add("decreased");
}
}
}
return USDIRR;
}
function getXHRRequest(){
var XHR = new XMLHttpRequest();
XHR.open("GET","https://api.coindesk.com/v1/bpi/currentprice.json");
XHR.onreadystatechange = function(){
if(XHR.readyState == 4 && XHR.status == 200){
var parsedData = JSON.parse(XHR.responseText);
price.innerHTML = parseFloat(parsedData.bpi.USD.rate_float).toFixed(2);
if(priceinner >= parseFloat(parsedData.bpi.USD.rate_float).toFixed(2)){
price.classList.add("increased");
}
else {
price.classList.add("decreased");
}
currency_symbol.innerHTML = parsedData.bpi.USD.symbol;
}
}
return XHR;
}
It was expected to change the class to "increased" when the price goes up. but it just remains decreased.

How to use variable from one method in another?

How to use site variable value from onreadystatechange method in soap method?
My code:
soap(value) {
var siteValue = '';
var xmlhttp = new XMLHttpRequest();
xmlhttp.open('POST', 'URL', true);
var to_json = require('xmljson').to_json;
var sr = xyz
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
soapres = xmlhttp.responseText;
this.soapresponse(soapres);
to_json(soapres, function(error, data) {
var a = data['soapenv:Envelope']['soapenv:Body']['wss:readResponse']['readReturn']['resultXml']['_'];
var jsonR = JSON.parse(a);
var sitee = jsonR.SALFCY; //site
siteValue = JSON.stringify(sitee);
alert(siteValue);
});
}
}
}
}

Categories

Resources