Handle error: "Uncaught Typeerror: Cannot read Property of 'value' Undefined"

Asked

Viewed 14,983 times

3

Hello,

When making an AJAX request, I have the following error:

Uncaught TypeError: Cannot read property of 'rede' undefined.

Until I understand the reason, I do not have the following value on account of the filter made by the user not return results when stamping the values within the code, but is it possible to treat this error? Like, put a 0 or something just so as not to interrupt reading the rest of my code?

This is my request, note the console.log trying to visualize the return and how the console returns the log:

$("#botao-filtrar").click(function(e){
    e.preventDefault();
    $.ajax({
        url: 'datacenter/functions/filtraDashboardGeral.php',
        async: true,
        type: 'POST',
        dataType: 'JSON',
        data: {rede: $("#dropdown-parceria").val(), codLoja: $("#dropdown-loja").val(), mes: $("#dropdown-mes").val()},
        success: function(data){
            console.log(data[1]['rede']);   
        }
    });

inserir a descrição da imagem aqui By default, data is an array that has an extension 3:

inserir a descrição da imagem aqui

But sometimes, depending on the option selected by the user, it only returns one or two keys because it has no data for another key.

Following example:

And here is the PHP:

<?php
    session_start();
    require_once('../../includes/gestaoOriginacao.php');

    $rede = $_POST['rede'];
    $codLoja = $_POST['codLoja'];
    $mes = $_POST['mes'];
    $nomeCompleto = $_SESSION['nomeCompleto'];

    $dados = array();
    $query = retornaQueryGrafico($rede, $codLoja, $mes, $nomeCompleto);

    $resultado = mysqli_query($conexao, $query);

    while($valores = mysqli_fetch_assoc($resultado)){
         array_push($dados, $valores);
    }

    echo json_encode($dados);

    function retornaQueryGrafico($rede, $codLoja, $mes, $nomeCompleto){
        $hierarquia = $_SESSION['hierarquia'];
        if($hierarquia == 1){
            $query = "SELECT * FROM evolucao_originacao WHERE redeTratada = '{$rede}' and codLoja = '{$codLoja}' and mesReferencia = '{$mes}' and supervisor = '{$nomeCompleto}' order by mesReferencia";
        } else {
            $query = "SELECT * FROM evolucao_originacao WHERE redeTratada = '{$rede}' and codLoja = '{$codLoja}' and mesReferencia = '{$mes}' and supervisor = '9999999' order by mesReferencia";
        }
        return $query;
    };
  • 1

    Put the value of data please.

  • Instead of console.log(data[0]['rede']);, shouldn’t be console.log(data.rede)?

  • Put the datacenter/functions/filtraDashboardGeral.php, the problem is in him.

  • I tried to explain a little how comes the result of the request

  • Edit the image and show open keys (or copy and paste the console here which is easier than image), so we know which is the return.

  • @Guilhermenascimento I edited with images and censored in some places on account of having confidential information. But I think it’s possible to visualize the structure of the object.

  • Just do it success: function(data){&#xA; console.log(data[1]); &#xA; } and see what returns.

  • @Guilhermenascimento he returns a undefined

  • @jvbarsou does so success: function(data){ console.log(data, data[1]); } copy the result and put it in Pastebin.com and paste the link here (delete sensitive data such as phones)

  • @Guilhermenascimento he returned that: [] undefined, without extension.

  • Returned [] is because the result came empty. Then you can do an if like this if (data.length) { popula os dados aqui }

Show 6 more comments

2 answers

3


From what I understand is not a PHP error, what is occurring is that probably depending on from query to variable data is coming empty [], then just make an IF to check:

$("#botao-filtrar").click(function(e){
    e.preventDefault();
    $.ajax({
        url: 'datacenter/functions/filtraDashboardGeral.php',
        async: true,
        type: 'POST',
        dataType: 'JSON',
        data: {rede: $("#dropdown-parceria").val(), codLoja: $("#dropdown-loja").val(), mes: $("#dropdown-mes").val()},
        success: function(data){
            if (data.length > 0) {
                //Atualiza a tela
            } else {
                //Exibe um alert(); ou outra coisa que avise que não retornou resultados
            }
        }
    });
});

Don’t forget to add the "error":, is good to check, can exchange for . done and . fail also:

$("#botao-filtrar").click(function(e){
    e.preventDefault();
    $.ajax({
        url: 'datacenter/functions/filtraDashboardGeral.php',
        async: true,
        type: 'POST',
        dataType: 'JSON',
        data: {rede: $("#dropdown-parceria").val(), codLoja: $("#dropdown-loja").val(), mes: $("#dropdown-mes").val()}
    }).done(function (data) {
        if (data.length > 0) {
            //Atualiza a tela
        } else {
            //Exibe um alert(); ou outra coisa que avise que não retornou resultados
        }
    }).fail(function (erro) {
        alert(erro);
    });
});
  • 1

    Thank you @Guilherme, I will adapt my code for this function, but I have already run some tests and it is possible to treat it the way you have! Thank you!!!

1

You can check if the property exists, in negative create one with a default value:

success: function(data){
    // verifica se é undefined
    if (!data[0]){
        data = [{rede: ''}]; // seta vazio para a propriedade rede do objeto no array
    }
}
  • 1

    What if data[0] is an object with several properties less rede?

  • 1

    The error indicates that data[0] that is Undefined, if only network does not exist the return will only be undefined @jbueno. Jsfiddle

  • 1

    Sorry, but that doesn’t solve the problem, the problem is in datacenter/functions/filtraDashboardGeral.php, have to see what returns, then just fix in Js.

  • 1

    In fact I only pointed out the problem of your answer without considering the question. Considering the question, your answer makes no sense because if data[0] is undefined it makes no sense to search for a property within it.

  • 1

    Agree @Guilhermenascimento, for this reason I also asked the AP to show exit. Because even falling into Success, maybe have some return.

  • 1

    @Lucascosta seriously, I think a huge headache answer what is not clear or can not be reproduced, the best in these cases is to vote to close, if it does not generate more confusion than anything else. Closure isn’t deleting, it’s just preventing a bad question from receiving answers and then totally changing the meaning by invalidating the answers. Do you understand? Everything has a good reason to exist on the site.

  • I gave an option to treat the error in js, as the AP asked in the question @jbueno, since the result undefined may occur with some specific type of filter. But the ideal solution is what Guilhermenascimento proposed, treat in PHP.

  • 1

    @Lucascosta, think with me. Cannot read Property 'network' of undefined. -> Cannot read network property of undefined". Who’s undefined is the parent object of rede.

  • @jbueno, I thought. In my thought the network father is data[0]. Or traveling? :/

  • 1

    Yes! That’s right. And what is the sense of searching for rede inside undefined????

  • No reason, my fault :p

Show 6 more comments

Browser other questions tagged

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