简体   繁体   中英

Sending json object across using POST request AJAX

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

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...!");
});

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM