ACS simple query with JS
by Thomas Roca
HTML
<h2> American Community Survey API with JavaScript</h2>
<p id="metropolitan"></p>
<table>
<th>Total population </th> <th id="total_population"></th> </tr>
<th>Black or African American </th><th id="black_african_american"></th>
</table>
CSS
h1, h2 {font-family:Calibri; font-weight: 1; margin-top:50px;}
h3 {font-family:Calibri; font-weight:bold}
p,li,th {font-family:Calibri;font-weight:400}
text {color: #f66d00;}
table, th, td { border: 1px solid #aeaeb2; border-collapse: collapse;}
th, td {padding: 10px; text-align:left}
JavaScript
$(function() {
// query the API
$.ajax({
url: "https://api.census.gov/data/2018/acs/acs1/spp?get=NAME,S0201_246E&POPGROUP=001&POPGROUP=004&for=metropolitan%20statistical%20area/micropolitan%20statistical%20area:35620",
complete: function(json) {
// get the API response
data = JSON.parse(json.responseText);
// set some variable to host data:
value_total = data[1][1]; // Poverty rate for total population
value_b = data[2][1]; // Poverty rate for Black and African American
metro = data[1][0]; // name of the metropolitan area
// let's add some text to be displayed on the web page
metro_text = "<b>Table 1.</b> Poverty rate in <text>" + metro+"</text>"
total_text = "<text>" + value_total + "% </text>"
black_african_american_text = "<text>" + value_b + "%</text>"
// let's send this tex to the actual web page using elements ids
document.getElementById("metropolitan").innerHTML = metro_text;
document.getElementById("total_population").innerHTML = total_text;
document.getElementById("black_african_american").innerHTML = black_african_american_text;
}
})
})