Why can not I get ajax request data? (json)

1

I have the following code:

script.js:

function maisDetalhes(id){
$.ajax({
url:'paginaDados.php',
type:'GET',
data:'id='+id,
dataType:'json',
success:function(data){
   alert(data.id_event);
 }
});

and pageDados.php:

foreach ($Dados as $Linhas) {      
  $resultado = array("id_evento" => $Linhas['id_event'],
  "nome_evento" => $Linhas['event_name'] );    
}

echo json_encode($resultado);

exit();

But in the ajax success function, I am not able to receive the data, when I give the alert it shows 'undefined', when I write only alert (data) it appears everything, however I would like to take the data separately, as Can I do it?

Thank you in advance!

    
asked by anonymous 17.09.2016 / 01:12

1 answer

2

This is because the date variable is not a JSON object but a String. To make it an Object, use the JSON parse of JavaScript like this:

function maisDetalhes(id){
    $.ajax({
       url:'paginaDados.php',
       type:'GET',
       data:'id='+id,
       dataType:'json',
       success:function(data){
          var obj = JSON.parse(data);
          alert(obj.id_event);
       }
    });

}
    
17.09.2016 / 01:20