Using Variables in an API

- 1 answer

Ad

I don't understand what I am doing wrong. Here is a link to a list of variables that I am using from the US Census: http://api.census.gov/data/2013/pep/natstprc/variables.json

I do realize that you can already see the name of the state from the drop down, but my ultimate goal is to be able to select a state from the drop down and have the population and population density, along with the state ID value or the state name (I don't care at this point because I am frustrated :( )appear. I was experimenting with state name first before I moved onto pop or pop density.

What am I doing wrong? Debugger didn't really help me too much. The error message that I get is

Cannot read property 'label' of undefined

In particular, here is the variable that I am using:

variables: {
STNAME: {
label: "State name",
concept: "Selectable Geographies"
},

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <link rel="stylesheet" target="_blank" rel="nofollow noreferrer" target="_blank" rel="nofollow noreferrer" href="css/style.css"></link>
</head>
<body>
    <section id="title">
        <h1>United States Population Search</h1>
        <hr/>
    </section>
    <section id="inputArea">
        <form>
            <select id="inputBox">
                <option value="01">Alabama</option>
                <option value="02">Alaska</option>
                <option value="04">Arizona</option>
                <option value="05">Arkansas</option>
                <option value="06">California</option>
                <option value="08">Colorado</option>
                <option value="09">Connecticut</option>
                <option value="10">Delaware</option>
                <option value="11">District of Columbia</option>
                <option value="12">Florida</option>
                <option value="13">Georgia</option>
                <option value="15">Hawaii</option>
                <option value="16">Idaho</option>
                <option value="17">Illinois</option>
                <option value="18">Indiana</option>
                <option value="19">Iowa</option>
                <option value="20">Kansas</option>
                <option value="21">Kentucky</option>
                <option value="22">Louisiana</option>
                <option value="23">Maine</option>
                <option value="24">Maryland</option>
                <option value="25">Massachusetts</option>
                <option value="26">Michigan</option>
                <option value="27">Minnesota</option>
                <option value="28">Mississippi</option>
                <option value="29">Missouri</option>
                <option value="30">Montana</option>
                <option value="31">Nebraska</option>
                <option value="32">Nevada</option>
                <option value="33">New Hampshire</option>
                <option value="34">New Jersey</option>
                <option value="35">New Mexico</option>
                <option value="36">New York</option>
                <option value="37">North Carolina</option>
                <option value="38">North Dakota</option>
                <option value="39">Ohio</option>
                <option value="40">Oklahoma</option>
                <option value="41">Oregon</option>
                <option value="42">Pennsylvania</option>
                <option value="44">Rhode Island</option>
                <option value="45">South Carolina</option>
                <option value="46">South Dakota</option>
                <option value="47">Tennessee</option>
                <option value="48">Texas</option>
                <option value="49">Utah</option>
                <option value="50">Vermont</option>
                <option value="51">Virginia</option>
                <option value="53">Washington</option>
                <option value="54">West Virginia</option>
                <option value="55">Wisconsin</option>
                <option value="56">Wyoming</option>
            </select>
            <input type="submit" class="searchButton"  value="Search"/>
            <hr/>
        </form>
    </section>
    <section class="searchResults">
        <div class="hiddenTemplates">
            <dl class="stateInformation">
                <dt><u>State ID Value:</u></dt>
                    <dd class="stateName"></dd>
                <dt><u>Population Amount:</u></dt>
                    <dd class="statePopulation"></dd>
                <dt><u>Population Density:</u></dt>
                    <dd class="statePopulationDensity"></dd>
            </dl>
            <div class="errorMessage">
                <p><b>Error Message: Something has gone wrong, try your search again.</b></p>
            </div>

        </div>
    </section>
    <script src="http://code.jquery.com/jquery-latest.min.js"></script>
    <script src="js/app.js"></script>
</body>
</html>

JavaScript/jQuery:

var data = { "variables": {
"for": {
  "label": "Census API FIPS 'for' clause",
  "concept": "Census API Geography Specification",
  "predicateType": "fips-for",
  "predicateOnly": true
},
"in": {
  "label": "Census API FIPS 'in' clause",
  "concept": "Census API Geography Specification",
  "predicateType": "fips-in",
  "predicateOnly": true
},
"STATE": {
  "label": "Total for US",
  "concept": "Selectable Geographies"
},
"NIM": {
  "label": "Net International Migration",
  "concept": "Estimate Variables",
  "predicateType": "int"
},
"STNAME": {
  "label": "State name",
  "concept": "Selectable Geographies"
},
"POP": {
  "label": "Resident population total",
  "concept": "Estimate Variables",
  "predicateType": "int"
},
"SUMLEV": {
  "label": "Geographic Summary Level",
  "concept": "Selectable Geographies"
},
"RESIDUAL": {
  "label": "Final residual for total pop",
  "concept": "Estimate Variables",
  "predicateType": "int"
},
"DIVISION": {
  "label": "Census Division Code",
  "concept": "Geographic Characteristics"
},
"DOM": {
  "label": "Net Domestic Migration of total Pop",
  "concept": "Estimate Variables",
  "predicateType": "int"
},
"DENSITY": {
  "label": "Population Density",
  "concept": "Estimate Variables",
  "predicateType": "int"
},
"BIRTHS": {
  "label": "Total Births",
  "concept": "Estimate Variables",
  "predicateType": "int"
},
"DATE": {
  "label": "Estimate Date",
  "concept": "Estimate Variables",
  "required": true,
  "predicateType": "int"
},
"REGION": {
  "label": "Census Region Code",
  "concept": "Geographic Characteristics"
},
"DEATHS": {
  "label": "Total Deaths",
  "concept": "Estimate Variables",
  "predicateType": "int"
}
 }
};


//This function fills in the result,
//in our results box, this will give us the name of the US State
var showStateInformation = function(data){

    //var myTest = data.variables.STNAME;
    var label = data.variables.STNAME.label;

    //Puts the name of the state into the state name area
    //var nameOfState = $('.stateName');
    //nameOfState.text(stateSearch);
    //var result = $('.searchResults . hiddenTemplates .stateInformation');
    var nameOfState = $('.stateName');
    nameOfState.text(label);
    //in our results box, this will give us the population for that state
    //based on the Census Data
    //var statePopAmount = result.find('.statePopulation');
    //statePopAmount.text(population);
    //in our results box, this will give us the population density for that state
    //based on the Census Data
    //var statePopDensity = result.find('.statePopulationDensity');
    //statePopDensity.text(populationDensity);

}

//The error message
var showError = function(error){
        var errorElem = $('.searchResults .errorMessage');
        var errorText = '<p>' + error + '</p>';
        errorElem.append(errorText);
}

//This function retrieves the said data
//http://www.census.gov/data/developers/data-sets/population-estimates-and-projections.html
//US, State, and PR Total Population and Components of Change

var getStateInformation = function(stateID){
    //the parameters that we need to pass in our request to the US CENSUS API
    var request = {
        "get": "STNAME",
        "DATE": "6",
        "for": "state:" + stateID,

        "key": 'I was told not to post the key publicly online'
    }

    $.ajax({

        type: "GET",
        data: request,
        url: "http://api.census.gov/data/2013/pep/natstprc",
        dataType: "json",
    })
    //What the function should do if successful
    /*.done(function(){
        var variables = $('#inputBox').val();
        showStateInformation(variables);
    })*/
    .done(showStateInformation)

    //What the function should do if it fails
    .fail(function(jqXHR, error){
        var errorElem = showError(error);
    })


}

$(document).ready(function() {

    /*Clicking the Search Button*/
    $('.searchButton').on('click',function(event){
        event.preventDefault();
        var stateID = $('#inputBox').val();
        getStateInformation(stateID);

    })
})
Ad

Answer

Ad

You have to declare and initialized your object properly

variables = {};
variables: {
label: "State name",
concept: "Selectable Geographies"
};

EDIT: It turned out you edit the question to make it more clear. So the data is fetch from the US Census API. The only thing you have to do is access the object property properly. Assuming this is the data you fetch from the US Census:

var data = { "variables": {
"for": {
  "label": "Census API FIPS 'for' clause",
  "concept": "Census API Geography Specification",
  "predicateType": "fips-for",
  "predicateOnly": true
},
"in": {
  "label": "Census API FIPS 'in' clause",
  "concept": "Census API Geography Specification",
  "predicateType": "fips-in",
  "predicateOnly": true
},
"STATE": {
  "label": "Total for US",
  "concept": "Selectable Geographies"
},
"NIM": {
  "label": "Net International Migration",
  "concept": "Estimate Variables",
  "predicateType": "int"
},
"STNAME": {
  "label": "State name",
  "concept": "Selectable Geographies"
},
"POP": {
  "label": "Resident population total",
  "concept": "Estimate Variables",
  "predicateType": "int"
},
"SUMLEV": {
  "label": "Geographic Summary Level",
  "concept": "Selectable Geographies"
},
"RESIDUAL": {
  "label": "Final residual for total pop",
  "concept": "Estimate Variables",
  "predicateType": "int"
},
"DIVISION": {
  "label": "Census Division Code",
  "concept": "Geographic Characteristics"
},
"DOM": {
  "label": "Net Domestic Migration of total Pop",
  "concept": "Estimate Variables",
  "predicateType": "int"
},
"DENSITY": {
  "label": "Population Density",
  "concept": "Estimate Variables",
  "predicateType": "int"
},
"BIRTHS": {
  "label": "Total Births",
  "concept": "Estimate Variables",
  "predicateType": "int"
},
"DATE": {
  "label": "Estimate Date",
  "concept": "Estimate Variables",
  "required": true,
  "predicateType": "int"
},
"REGION": {
  "label": "Census Region Code",
  "concept": "Geographic Characteristics"
},
"DEATHS": {
  "label": "Total Deaths",
  "concept": "Estimate Variables",
  "predicateType": "int"
}
 }
};

The way to access it is:

var label = data.variables.STNAME.label

The way you are doing now is a bit wrong. It should be something like this.

var showStateInformation = function(data){

  var myTest = data.variables.STNAME;

// OMIT THE REST OF THE CODE
}

If the data is still in type of string, you need to parse it first. But I strongly suggest you do it before calling this function and return a proper object. But for now, try to check first

if (typeof data == 'string') {
  data = JSON.parse(data}
}

EDIT: It turned out the url used in JQuery is different with the API url in the text. That is another bugs found:

var getStateInformation = function(stateID){
//the parameters that we need to pass in our request to the US CENSUS API
var request = {
"get": "STNAME",
"DATE": "6",
"for": "state:" + stateID,

"key": 'I was told not to post the key publicly online'
}

$.ajax({

type: "GET",
url: "http://api.census.gov/data/2013/pep/natstprc/variables.json"
})
//What the function should do if successful
.done(function(data){
console.log(data.variables.STNAME);
})

//What the function should do if it fails
.fail(function(jqXHR, error){
var errorElem = showError(error);
})


}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Ad
source: stackoverflow.com
Ad