Handle error: "Uncaught TypeError: Can not read property of 'value' undefined"

3

Hello,

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

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

I even understand the reason, I do not have the following value on account of the filter made by the user not returning results at the time of stamping the values inside the code, however is it possible to handle this error? Type, put a 0 or something of the type just to not stop reading the rest of my code?

This is my request, note the console.log trying to view 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']);   
        }
    });

Bydefault,dataisanarraythathasa3extension:

Butsometimes,dependingontheoptionselectedbytheuser,itonlyreturnsoneortwokeysbecauseitdoesnothavedataforanotherkey.

Here'sanexample:

AndhereisPHP:

<?phpsession_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);}echojson_encode($dados);functionretornaQueryGrafico($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;
    };
    
asked by anonymous 20.01.2017 / 19:35

2 answers

3

As I understand it is not a PHP bug, what is happening is that depending of the query the variable data is coming empty [] , so just do 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
            }
        }
    });
});

Do not forget to add "error": , it's good to check, you can exchange for .done and .fail too:

$("#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);
    });
});
    
20.01.2017 / 20:59
1

You can check if the property exists, if not 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
    }
}
    
20.01.2017 / 19:46