Undefined when attempting to use the valid JSON received

0

I have a boring problem of finding the error, I'm already looking for hours here. I'm getting a JSON from PHP using JQuery, I can see it as you can see below the result of the answer "date":

{
    "sucesso": 1,
    "dados": {
        "BTC_YAMRUB": {
            "result": 500000,
            "url_redirect": "https:\/\/mysite.com\/?rid=1229109",
            "https": 1,
            "link_permanente": "mysite",
            "nome": "MySite",
            "exchange_rates": 500000,
            "idade": "3 anos e 1 m\u00eas",
            "wmid": null,
            "pais_nome": "Brasil",
            "moeda_from": "Bitcoin BTC",
            "moeda_to": "Yandex money RUB",
            "rank_from": "14",
            "rank_to": "38",
            "reviews": [{
                "cliente_site": "52",
                "positivo": "0",
                "comentario": "0",
                "negativo": "0"
            }],
            "offer": {
                "from": 0,
                "to": 0,
                "in": 1,
                "out": 500000,
                "amount": 121436.1859,
                "minfee": 0,
                "fromfee": 0,
                "tofee": 0,
                "minamount": 0,
                "param": "manual"
            }
        }
     }
}

however when trying any of the lines below I get undefined .

console.log(data[0].length);
console.log(data.length);
console.log(data.dados.length);

The javascript code:

function getRates()
{
    $("#gif_load").show();

    $.post(URL_SITE + '/api/exchangers', {from: $("#from").val(), to: $("#to").val()}, function(data, textStatus, xhr) {

        if(textStatus == "success") {

            $("#exchangers tbody tr").remove();

            console.log(data.length); // undefined
            console.log(Object.keys(data).length); // 2

            if(data.dados.length > 0)
            {
                  $.each(data.dados, function(index, el) {
                      console.log(el.result);
                  });
            }
          }

     });

}

The PHP code:

<?php
ini_set('display_errors', 1);
include_once(dirname(__FILE__)."/../includes/_conect.php");

$limit_blocktraill = 300;

header('Content-Type: application/json');
$url_invalid  = URL_SITE . '/';
$url_valid = str_replace(":80", "", $url_invalid);

if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest' && strpos($_SERVER["HTTP_REFERER"], $url_valid) !== false)
{
    if(isset($_POST["from"]) && isset($_POST["to"]))
    {
        $from = mysqli_real_escape_string($_POST["from"]);
        $to = mysqli_real_escape_string($_POST["to"]);

        #--------------------MemCached-----------------------------------------
        $memCached = new Memcached();
        $memCached->addServer('localhost', 11211);

        if ($dados = $memCached->get('rank_moeda')) {
            if ($memCached->getResultCode() == Memcached::RES_NOTFOUND) {
                $exchangers = 0;
            }else{
                $exchangers = $dados;
            }
        }

        if(count($exchangers) > 0)
        {
            echo json_encode(array("sucesso" => 1, "dados" => $exchangers));

        }else{
            echo json_encode(array("sucesso1" => 1, "dados" => array()));
        }

    }else{
        echo json_encode(array("sucesso2" => 0, "Erro" => "Error"));
    }

}else{
    echo json_encode(array("sucesso3" => 0, "Erro" => "Error"));
}

I checked the entire answer on the link and it's OK. Any other tests I can do to find out what's going on?

    
asked by anonymous 23.02.2018 / 03:12

2 answers

1

It turns out that JavaScript does not return the size of the object, just arrays . So you're giving the error undefined .

Remembering that every time you return (see the brackets in the example below) :

{
    "sucesso": 1,
    "dados": [{
        ...
    }]
}
JavaScript will interpret as a JSON Array and will automatically add the length property.

And every time you return:

{
    "sucesso": 1,
    "dados": {
        ...
    }
}

JavaScript will interpret as a JSON Object and will not add property length

But there is a way to traverse an object. Just return all keys of the object and then execute a for..of .

Example:

$.post('SUA-URL', {}, function(data, textStatus, xhr) {

    if(textStatus == "success") {

        $("#exchangers tbody tr").remove();

        /* Captura as keys */
        let keys = Object.keys(data.dados);

        /* Exibe a quantidade */
        console.log( keys.length );

        /* Verifica se há keys */
        if ( keys ) {

            /* Percorre os valores através da key */
            for (let d of keys) {
                console.log( data.dados[d]);
            }
        }
      }

 });

Or you can return all values with Object.values .

Example:

$.post('SUA-URL', {}, function(data, textStatus, xhr) {

    if(textStatus == "success") {

        $("#exchangers tbody tr").remove();

        /* Captura todos os valores */
        let values = Object.values(data.dados);

        /* Exibe a quantidade de valores */
        console.log( values.length );

        /* Verifica se há valores disponíveis */
        if ( values ) {

            /* Percorre todos os valores */
            for (let v of values) {
                console.log( v );
            }
        }
      }

 });
    
23.02.2018 / 04:38
0

Look, the data should be counted like this:

Object.keys(data).length // retorna 2

Data:

Object.keys(data.dados).length // retorna 1

To simplify, you can:

var tmp = Object.keys(data);
console.log(tmp.length);
console.log(tmp.dados.length);
    
23.02.2018 / 03:37