Reputation: 105
I am new to web development and I am trying to figure out how to display an image based on a response from getJSON. The data being received is from a REST API. The data is then stored in 2 arrays, humid and date. Humid contains the humidity as a string. The humid array is then converted to an Integer array- humid_final. I wanted to know how I could display a certain image on the screen based on a particular value in the humid_final array.
If the latest entry in humid_final array= 50 display image A. Else display image B. (where image A,B are static images stored locally).
$(function updat() {
var url = "https://xpm4zyor39.execute-api.us-west-2.amazonaws.com/prod/entries";
var humid = [],
date = [],
humid_final = []
$.getJSON(url, function (json) {
$(json['Items']).each(function(i, data) {
//Store indicator name
// fill the date array
humid.push(data.humidity);
// fill the string data array
date.push(data.Date);
});
console.log(date);
// query send string that we need to convert into numbers
for (var i = 0; i < humid.length; i++) {
if (humid[i] != null) {
humid_final.push(parseFloat(humid[i]))
} else {
humid_final.push(null)
};
}
var chart = new Highcharts.Chart({
chart: {
type: 'spline',
renderTo: 'container'
},
title: {
text: 'indicatorName'
},
tooltip: {
valueDecimals: 2,
pointFormat: '<span style="color:{point.color}">\u25CF</span> {series.name}: <b>{point.y}%</b><br/>'
},
plotOptions: {
series: {
marker: {
enabled: false
}
}
},
subtitle: {
text: 'Source: World Bank Data'
},
xAxis: {
categories: date //.reverse() to have the min year on the left
},
series: [{
name: 'humidity',
data: humid_final //
}]
});
}); //getJSON method
setTimeout(updat, 3000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<script src= "opendataAPI.js"></script>
<div id="container" style="min-width: 310px; height: 400px; margin: 0 auto"></div>
Upvotes: 2
Views: 192
Reputation: 902
You're almost there. Give the image tag in your html an id and make it point to the standard image imageB like <img id="changingImage" src="./images/imageB.png" />
Then let's try to translate this ...
If the latest entry in humid_final array= 50 display image A. Else display image B.
into javascript:
if (humid_final[humid_final.length-1] == 50) {
document.getElementById('changingImage').src="./images/imageA.png";
}
Upvotes: 2