Error accessing JSON with Ajax jquery

Asked

Viewed 181 times

0

I’m getting a JSON that I created with PHP as described below, however, when I try to access the properties of this JSON he always returns to 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 to me the JSON straight

Someone can help?

Function PHP 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);
}

Function JS who accesses the 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);
        }
    });
}
  • How’s the checkUser.php file?

  • Is this php function ai

  • You want to return only 1 bank record or all?

  • I want the whole bank.

  • If it is all, it will return several data.crs_id... which one you want to capture in particular or want to capture all?

  • I need all of you.

  • I made a change in my reply, but see if any of the two answers.

Show 2 more comments

1 answer

1


You’re getting a JSON Array, so it is not possible to access the property crs_id directly, this requires using a loop loop or using the index:

Example with 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);
    }
});

Example with loop loop:

$.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);
        }
    }
});
  • How to send this json without being array?

  • You must use the echo json_encode( $stmt->fetch() );, but will only return one registration only.

Browser other questions tagged

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