0

I am new to APIs and I want to add the USDA Nutrients database api to my website. I want the user to be able to search for the food,select one of the appeared results and see its' nutrition information.

How can I do this in plain JS? I've created a search bar in my website and JS takes the input and requests the data from the USDA api.

var apiKey = '';
var q = "eggs";

var url = "http://api.nal.usda.gov/ndb/search/?format=json&q=" + q + "&sort=n" + "&max=25" + "&offset=0" + "&api_key=" + apiKey;

var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);



xhr.onreadystatechange = function() {

  if (xhr.readyState === 4)  {
  var data = JSON.parse(this.responseText);
  document.querySelector("#usdaResults").innerHTML = data.body;
  }
};
xhr.send();

I want first to present to the user a list of the results of what they searched. Then after they click the food, I want to present its' nutritional information(protein etc).

EDIT: When a user searches a food, I want to display the "group" , "name"and "manu" of all available results. At the same time,when a user wants to see the nutrition information for a specific food of those listed, I want to get its' "ndbno" number and look into the USDA database for it so I can display the data after. Same way as displayed in the official website: https://ndb.nal.usda.gov/ndb/search/list?SYNCHRONIZER_TOKEN=c91f87b5-59c8-47e0-b7dc-65b3c067b7ff&SYNCHRONIZER_URI=%2Fndb%2Fsearch%2Flist&qt=&qlookup=egg+potato&ds=&manu=

EDIT2: I'm getting this error now. undefined,0 results found

var apiKey = '';
var q = document.getElementById('search').value;

var url = "http://api.nal.usda.gov/ndb/search/?format=json&q=" + q + "&sort=n" + "&max=25" + "&offset=0" + "&api_key=" + apiKey;

var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);

function getData() {
xhr.onreadystatechange = function () {  
    if (xhr.readyState === 4 && xhr.status === 200) {  
          console.log(xhr.responseText)
          var data = JSON.parse(this.responseText);
if (data && data.list && data.list.item) {
  var html = "";
  data.list.item.map(item => {
    let string = "<p>Name: " + item.name + " Manu: " + item.manu + " Group: " + item.group + "<p>";
    html += string;
  })
}
document.querySelector("#usdaResults").innerHTML = html;
    }
       else {  
           console.log("Error", xhr.statusText);  
        }  
    }
xhr.send();
  }

HTML:

<section class="usda"> 
        <h1>USDA Nutrients Database</h1>
        <form id="search">
            <input type="text" placeholder="Search.." name="search">
            <button type="button" onclick="getData();">Search</button>
          </form>
          <div id="usdaResults"></div>
    </section>
F4-E
  • 47
  • 6

1 Answers1

1

So, it may be that there are errors with your XHR call - however we can catch and log those errors. You want to open your developer tools in your browser (usually right click > developer tools) to look at the JS logs.

I'm getting: VM131:20 GET http://api.nal.usda.gov/ndb/search/?format=json&q=eggs&sort=n&max=25&offset=0&api_key= 403 (Forbidden)

But that's because I have no API Key. If you do not, you'll need to get an API key from them.

I have grabbed some code from another SO post, here:

var apiKey = '';
var q = "eggs";

var url = "http://api.nal.usda.gov/ndb/search/?format=json&q=" + q + "&sort=n" + "&max=25" + "&offset=0" + "&api_key=" + apiKey;

var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);



xhr.onreadystatechange = function (oEvent) {  
    if (xhr.readyState === 4) {  
        if (xhr.status === 200) {  
          console.log(xhr.responseText)  
        } else {  
           console.log("Error", xhr.statusText);  
        }  
    }  
}; 
xhr.send();

Reference:

XMLHttpRequest (Ajax) Error

EDIT:

For the response, once you have parsed the JSON - you can get all the available name, group and manu of the data as so - I've output the details in

tags, and this is untested - so maybe incorrect, but this is more for pseudo code.

var data = JSON.parse(this.responseText);
//Assuming data is valid!
if (data && data.list && data.list.item) {
  var html = "";
  data.list.item.map(item => {
    let string = "<p>Name: " + item.name + " Manu: " + item.manu + " Group: " + item.group + "<p>";
    html += string;
  })
}
document.querySelector("#usdaResults").innerHTML = html;
JRK
  • 3,686
  • 1
  • 13
  • 19
  • I just didn't include the API key for safety reasons. Okay, I'm getting the json data in the console log. How do I display it in the html though,in a better-looking way? https://i.imgur.com/5ORJ1Dq.png HTML CODE: ```

    USDA Nutrients Database

    ```
    – F4-E Jun 10 '19 at 13:48
  • Can you update your original post, with some details - what would you like to display in the HTML? You'll need to loop over the JSON for that. – JRK Jun 10 '19 at 13:52
  • @F4-E I've updated the post - could you perhaps accept the answer if your original problem is solved. – JRK Jun 10 '19 at 14:14
  • Sure, I'm just facing some problems. Please take a look again, I edited it. – F4-E Jun 10 '19 at 14:37
  • What query are you using? You really need to look at the API docs for this - SO are for general coding issues. – JRK Jun 10 '19 at 14:55
  • Sorry, what do you mean by query? I think it's not an API problem. The problem is the way I'm getting the value from the search input and pass it to the API. That's where I need help now because for some reason it doesn't give the value to "q". – F4-E Jun 10 '19 at 15:02
  • 1
    `var q = document.getElementById('searchValue').value;` Put an id on your input value, rather than the id for your form. So `` – JRK Jun 10 '19 at 15:17
  • Great, everything works now. Thank you very much! Any idea on how would I make the foods listed clickable so the user can see food's data? API documentation says that the ndbo number and a new request is needed for that. – F4-E Jun 10 '19 at 15:25