Just trying to get some practice working with public APIs in Javascript. All I want to do is, when you submit the query, have the list of items I get back be sorted alphabetically by the h4
value (food name). I tried calling .sort()
on the response item before calling .map()
. Tried directly sorting the div elements after the fact using jquery, but in both cases, I just get a blank page back. I'm very new to javascript and writing this all in Notepad++, so there's probably a much better way to be doing all this, but I'm not aware of it.
Html code:
<!DOCTYPE html>
<html>
<form action="search">
<label>Search</label>
<input type="text">
<input type="submit">
<input type="reset">
</form>
<div class="result">
<h3>Result</h3>
</div>
</html>
Css code:
.result{
display:flex;
flex-wrap:wrap;
}
.item{
min-width:200px;
margin:20px auto;
}
JavaScript code:
var apiKey = "4b314d3e9171fbe99c6cdf16127ba93e";
var apiId = "4c143c55";
var queryItem;
var url = 'https://trackapi.nutritionix.com/v2/search/instant?query=';
var form = document.querySelector('form');
var input = document.querySelector('input[type="text"]');
var result = document.querySelector('.result');
function search(e){
e.preventDefault();
queryItem = input.value;
makeRequest(queryItem);
input.value= "";
}
function reset(){
var node = document.querySelector('.result');
while (node.firstChild) {
node.removeChild(node.firstChild);
}
}
function createFood(name, qty, unit, photo){
var item = document.createElement('div');
var foodName = document.createElement('h4');
var serving = document.createElement('p');
var img = document.createElement('img');
item.classList.add('item');
foodName.innerHTML = name;
serving.innerHTML = qty+' '+unit;
img.src = photo;
result.appendChild(item);
item.appendChild(img);
item.appendChild(foodName);
item.appendChild(serving)
}
function makeRequest(queryItem) {
reset();
xhr = new XMLHttpRequest();
xhr.onload = function() {
var response = JSON.parse(this.responseText);
response.common.map(function(food){
createFood(food.food_name,
food.serving_qty,
food.serving_unit,
food.photo.thumb
)
})
};
xhr.open(
"GET",
url+queryItem,
true
);
xhr.setRequestHeader('x-app-id',apiId);
xhr.setRequestHeader('x-app-key',apiKey);
xhr.send();
}
form.addEventListener('submit', search)
form.addEventListener('reset', reset)