0

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 :)

2
  • 1
    Try replacing your first and last double-quotes with single-quotes. Commented Jul 22, 2014 at 18:05
  • 1
    Have you considered using jQuery to simplify the process? With jQuery it's very simple: $.post( "ajax/test.html", function( data ) { $( ".result" ).html( data ); }); (example is from the jQuery documentation). Commented Jul 22, 2014 at 18:05

2 Answers 2

1

Since it is a HTTP API request, you can call it directly. with $.getJSON method of Jquery. This worked for me.

$.getJSON("https://api.nutritionix.com/v1_1/search/Macdonald's?results=0%3A20&cal_min=0&cal_max=50000&appId=2629576d&appKey=YOUR_API_KEY_HERE", function(data2)
{
  alert(data2.total_hits);
}).fail(function(jqXHR, status, error)
{
 alert("error...!");
});
Sign up to request clarification or add additional context in comments.

Comments

0

When you need to send data via POST, you have to set data like this

xmlhttp.send("appId=XYZ&appKey=XYZ&query=Cheddar Cheese");

in php you will get your data like this :

echo $_POST['appId'] ; // shows XYZ
echo $_POST['appKey'] ; // shows XYZ
echo $_POST['query'] ; // shows Cheddar Cheese

If you need to send a data as json , you just need to do this

xmlhttp.send('data={"appId":"XYZ", "appKey":"XYZ","query":"Cheddar Cheese"}');

in your php file, you get the result like this

$Data = json_decode($_SESSION['data']);
echo $Data->appId; // shows XYZ
echo $Data->appKey; // shows XYZ
echo $Data->query; // shows Cheddar Cheese

1 Comment

Patrick's suggestion fixed it. Turns out that all I had to go was replace the " with '

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.