Why can’t I get the data from the ajax request? (json)

Asked

Viewed 507 times

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 in the 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 function sucess, 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, but I would like to take the data separately, as I can do?

Thank you very much in advance!

1 answer

2


This is because the data variable is not a JSON object but a String. To transform it into an Object the Javascript parse JSON is used this way:

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

}
  • Putssss, thank you very much man, really, I am very lay with ajax, and I was breaking my head to try to solve this, thank you very much

  • I suggest you use Firebug in Firefox, and instead of using Alert use console.log, because this way debuger tells you what type of variable is coming. It was a pleasure to help you.

Browser other questions tagged

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