Home > Enterprise >  Nothing happening after get JSON request
Nothing happening after get JSON request

Time:10-27

I am calling an API to return some data. I can see in dev tools the response is 200 successful, and in the network tab can see the returned data.

The problem I have is with displaying the data in my UI. At this stage all I want to do is display the returned data in an alert.

I have tried the following, but the alert doesn't fire. I can't see any errors in console, and if I visit the PHP file manually (substituting in the GET variables) there are no errors.

jQuery

$.getJSON('fetch.php', { getFiat: fiat, getCoin: coin, getLimit: limit, getAggregate: aggregate, getCall: 4 }, function(data) {
    alert(data);
}).fail(function (j, t, e) {
   console.log(e);
});

PHP

if($_GET['getCall'] == 4) {
    try {
        callAPI();
        $data = file_get_contents('https://min-api.cryptocompare.com/data/v2/histoday?fsym='.$_GET['getCoin'].'&tsym='.$_GET['getFiat'].'&limit='.$_GET['getLimit'].'&aggregate='.$_GET['getAggregate'].'&e=CCCAGG&api_key=[key]');
        $json = json_decode($data);

        if(isset($json->Response) != "Error") {
            echo $data;
        } else {
            echo "Broken duh..";
        }
    }

    //catch exception
    catch(Exception $e) {
        echo $e->getMessage();
    }
}

The API response looks like this: https://min-api.cryptocompare.com/data/v2/histoday?fsym=BTC&tsym=USD&limit=30&aggregate=1&e=CCCAGG

CodePudding user response:

This checks isset and then checks if it's NOT equal to "Error":

    if(isset($json->Response) != "Error") {

If it isset then it returns true which is == to "Error". You need two separate checks. Depending on what is returned in case of error, maybe:

    if(isset($json->Response) && $json->Response != "Error") {

Or check for success:

    if(isset($json->Response) && $json->Response == "Success") {
  • Related