Undefined when trying to use the received valid JSON

Asked

Viewed 271 times

0

I’m having a hard time finding the error, I’ve been looking here for hours. I am receiving a PHP JSON using Jquery, I can visualize it as 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"
            }
        }
     }
}

but while 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 code of PHP:

<?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 whole answer on https:/jsonlint.com/ and it’s OK. To some other test I can do to find out what’s going on?

  • It has how to put the JS code that makes and treats the request?

  • For now, I edited the question with the JS code.

  • I edited with PHP code too.

2 answers

1


It turns out that Javascript does not return the size of the object, only of arrays. That’s why you’re making the mistake Undefined.

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

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

Javascript will interpret as a JSON Array and automatically add the property length.

And every time you return:

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

Javascript will interpret as a JSON Object and nay will add the property length

But there is a way to go through an object. Just return all the 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 );
            }
        }
      }

 });
  • And how I would return so [{&#xA; "sucesso": 1,&#xA; "dados": {&#xA; ...&#xA; }&#xA;}] ?

  • 1

    @Perdugames with code (PHP) posted has no way of knowing much, but you should remove the values BTC_YAMRUB when saving variable values. It would be more or less like doing: $dados[] = $dados_da_moeda instead of $dados[ $id ] = $dados_da_moeda;

  • Got it, very good your answer, marking as solved, I appreciate the help, saved the dawn from the headache that would be to find out that this kkkkkk

  • I try to convert to array with (array) the "Offer", but I can’t either.

  • @Perdugames if possible edit your question put the code as you are storing these values in the variable. Or you can post to https://pastebin.com

  • That’s correct, it’s the "Offer" variable that is being assigned wrong for some reason. Instead of the string I’m getting 0.

  • I was converting it to float unintentionally because of this problem here https://answall.com/questions/278176/porque-o-php-retorna-zero-subtrair-elements-de-um-object. I ended up making a (float) on everything, but forgot the kkkk strings, now it’s correct.

Show 2 more comments

0

Look, the data should be counted like this:

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

Dice:

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

For simplicity you can do it like this:

var tmp = Object.keys(data);
console.log(tmp.length);
console.log(tmp.dados.length);
  • the ... just explaining that has more data, disregard it.

  • I figured it was, I edited the answer with more examples,

  • I took the test and it’s OK.

  • Sorry, I saved without finishing putting the details of the explanation. I hope I helped

  • But how do I use the data? and why does it have to be like this? I always did it the way it is above and it worked. I think the problem is something else.

  • To be frank I’ve never seen anyone measure the size of a key Json without being the way I showed it, I took the test with yours and it worked, but the way you showed it I only got with Arrays: [1,['a',b],'teste']

  • console.log(tmp); return me (2) ["sucesso", "dados"]&#xA;0&#xA;:&#xA;"sucesso"&#xA;1&#xA;:&#xA;"dados"&#xA;length&#xA;:&#xA;2&#xA;__proto__&#xA;:&#xA;Array(0) however console.log(tmp.dados.length); returns me undefined too.

  • You did the test straight on the console or calling the function?

  • calling the function.

  • You’re right, it didn’t even make sense the last example I made. I must be sleepy anyway

Show 5 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.