I'm a newbie dev trying to build a web app that makes use of nutritionx.com public APIS. I have the following piece of Javascript to fetch the fat content of 'Cheddar Cheese'
<script>
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var responseTxt = xmlhttp.responseText;
var obj = JSON.parse(responseTxt);
document.getElementById("myDiv").innerHTML=obj.hits[0].fields.nf_total_fat;
}
}
xmlhttp.open("GET","https://api.nutritionix.com/v1_1/search/cheddar%20cheese? fields=item_name%2Citem_id%2Cbrand_name%2Cnf_calories%2Cnf_total_fat&appId=XYZ&appKey=XYZ",true);
xmlhttp.send(); // works!
</script>
When I try to use POST, it doesn't work (I suspect that my request format for sending parameters is incorrect)
// What I tried:
// xmlhttp.open("POST","https://api.nutritionix.com/v1_1/search",true);
// xmlhttp.setRequestHeader("Content-type","application/json");
// xmlhttp.send("{"appId":"XYZ", "appKey":"XYZ","query":"Cheddar Cheese"}");
How to correctly send a Json object to a server that is requesting it using POST in Javascript? The API documentation gives the following sample:
curl -XPOST https://api.nutritionix.com/v1_1/search -H 'Content-Type: application/json' -d'
{
"appId":"YOUR_API_ID",
"appKey":"YOUR_API_KEY",
"query":"Cookies `n Cream"
}'
Is it necessary to use curl or php or can javascript suffice? Ideally I want something along the lines of what I tried. Thanks for reading :)
$.post( "ajax/test.html", function( data ) { $( ".result" ).html( data ); });(example is from the jQuery documentation).