Error using . length in AJAX response

Asked

Viewed 36 times

0

I have the following ajax.

    var ajax = new XMLHttpRequest();
    
    ajax.open("GET", 'http://localhost/erp/api/v1/itens.php');

    ajax.responseType = "json";

    ajax.send();
    ajax.addEventListener("readystatechange" , function () {
      
        if (ajax.readyState === 4 && ajax.status === 200){

          var response = ajax.response;

          console.log(response.length);  
          
        }
    })

However the Console.log(reponse.length) brings me 'Undefined', and if I print the reponse brings me 6 data, the PHP that brings the data is this.

      $i = 1;
      while($lista = $this->ListarDados()):
          $produtos[$i] = array(
                'idProduto'=> $lista['id_Produto'],
                'nomeProduto' => $lista['nomeProduto'],
                'referencia' => $lista['referencia'],
                'custo' => str_replace(".", ",", $lista['custo']),
                'venda' => str_replace(".", ",", $lista['venda']),
                'lucro' => str_replace(".", ",", $lista['lucro'])
           );
           $i++;
       endwhile;
       echo json_encode($produtos);

That’s the php answer

 {"1":{"idProduto":"20","nomeProduto":"teste","referencia":"as2","custo":"10,00","venda":"30,00","lucro":"20,00"},"2":{"idProduto":"21","nomeProduto":"Atacado do Body","referencia":"222","custo":"11,00","venda":"26,55","lucro":"15,55"}}

Someone can help me?

  • 1

    It is necessary to show what is returned from your PHP code. As we cannot as JSON is being formed or returned, it is difficult to give an answer. Please [Edit] your question by adding a [mcve]

  • Edited by @Wallacemaxters

  • I answered the question. The problem is in the indexes of your array.

1 answer

0

The problem is generated because its array has no "regular" indexes for it to be returned as an array in JSON. You started counting the array through 1 and not 0.

If you have this array below, it will fail:

$arr = [1 => 'zero', 2 => 'dois'];
echo json_encode($arr);

This will generate

{"1":"zero","2":"dois"}

This return is equivalent to a Object in Javascript and the same I do not have the value length.

The ideal in your case would be to use array_values to "reset indexes", since you want to return a JSON array.

echo json_encode(array_values($arr));

This will return:

["zero","dois"]

Tip 2

You can change your $i for 0. This will generate a "regular array" in PHP.

Tip 3

You can change

$produtos[$i] = array()

For:

$produtos[] = array()

This will add the items from array so that it begins from 0

This way, you will be able to access the length.

Tip 4

If you do not want to return the PHP output, just treat it by Javascript. Use Object.values to transform the values of Object in Array.

console.log(Object.values(response).length);  
  • 1

    Perfect, I didn’t know about this part of array_values(). Thank you very much@Wallacemaxters

Browser other questions tagged

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