Problem catching Json in AJAX

Asked

Viewed 183 times

0

I am trying to recover the data from my ajax request in json, they arrive correctly, but at the time I will use them only returns "Undefined".

$("#selecionada").on("submit",function(){

  var id_licaoselecionada = $("#prox").val();


  console.log("ID da Licão selecionada =  + "+id_licaoselecionada);

    $.ajax({
      url:'http://localhost/tempus/AJAX/licao/',
      type:'POST',
      data:{idlicao:id_licaoselecionada},
      datatype:'json',
      success:function(data){

        console.log(data)
        console.log("->"+data["nome"]);

        $("#myModal").modal("hide");
        $("#myModal2").modal("show");
        $("#NomeDaLicao").html(data["nome"]);
        $("#ImagemDaLicao").attr('src',data['icone']);
        console.log('Licão escolhida');
      },
      error:function(){
        console.log('Deu ruim, Lição nao carregada');
      }
    }) ;

    return false;

Console returns like this:

  • {"idlicoes":"3","0":"3","name":"Today goes","1":"Today goes","icone":"Assets/images/licoes/paper-plan-1.png","2":"Assets/images/licoes/paper-plan-1.png"}
  • ->Undefined
  • chosen lesson
  • try accessing the indexes with "." (dot) instead of "[]". Example, date.name

  • continues returning Undefined, before I was putting the Success:Function(json) [with json] and accessing the indices so with the point, but only gave ''udefinded"

  • 1

    What happens if you do the following? console.log(JSON.parse(data))

  • UHUUL! Worked out using JSON.parse() . Thank you so much for your help!

  • Cool! Just accept the answer, now :)

1 answer

0


What is happening is that you are holding a string in your hands and treating it as an object.

Do it this way:

data = JSON.parse(data);
console.log(data.nome); // data["nome"] funciona também, mas a primeira forma é a recomendada.

Browser other questions tagged

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