Error accessing JSON with Ajax jquery

0

I'm getting a JSON that I created with PHP as described below, but when I try to access the properties of that JSON it always returns me undefined .

I made these test files there to demonstrate how I'm doing.

If I give a console.log on the date, it returns me the JSON right

Can anyone help?

PHP function that returns me the JSON :

function listaAluno(){

    $conn = Conexao::pegaConexao();
    $stmt = $conn->prepare("SELECT * from tab_sys_student");
    $stmt->execute();
    $dados['data'] = $stmt->fetchAll(PDO::FETCH_ASSOC);

    echo json_encode($dados);
}

JS function that accesses JSON :

function listaCurso(){
    alert('listou');
    $.ajax({
        url: "restrict/checkUser.php",
        type: "POST",
        cache: false,
        dataType : 'json' ,/*adiciona o tipo de retorno*/
        error: function(){
            alert('Erro ao Tentar ação.');
        },
        success: function (data) {
            console.log(data.crs_id);
        }
    });
}
    
asked by anonymous 22.02.2018 / 21:04

1 answer

1

You are getting a JSON Array , so you can not access the crs_id property directly, so you need to use a loop or use the index:

Example Index:

$.ajax({
    url: "restrict/checkUser.php",
    type: "POST",
    cache: false,
    dataType : 'json' ,/*adiciona o tipo de retorno*/
    error: function(){
        alert('Erro ao Tentar ação.');
    },
    success: function (result) {
        alert('listou');

        console.log(result.data[0].crs_id);
        console.log(result.data[1].crs_id);
        console.log(result.data[2].crs_id);
        console.log(result.data[3].crs_id);
    }
});

Repeat loop example:

$.ajax({
    url: "restrict/checkUser.php",
    type: "POST",
    cache: false,
    dataType : 'json' ,/*adiciona o tipo de retorno*/
    error: function(){
        alert('Erro ao Tentar ação.');
    },
    success: function (result) {
        alert('listou');

        for (let d of result.data) { // Ou "(let d of result)"
            console.log(d.crs_id);
        }
    }
});
    
22.02.2018 / 21:12