jonny_89 jonny_89 - 12 days ago 9
Ajax Question

Jquery ajax issue, keep getting undefined as a result value

I'm a total newbie at using ajax and jquery's ajax wrapper function. Trying to get json from an API and append the result to the html of a site that I'm building.

Here's my code:

$.ajax({
type : 'GET',
url : 'api/v1/get_profesors.php',
success : function(data){
var content = 'Name : '+data.name ;
content += ' Surname : '+data.surname ;
content += ' Bio : '+data.bio ;
content += ' Instrument : '+data.instrument ;
$("#profesori").append(content);
}
});


The result which I'm getting is Name : undefined Surname : undefined Bio : undefined Instrument : undefined.

Oh, and here's part of the JSON which I'm receiving from the API:

{"id":7,"name":"adsssss","surname":"THERE I GO","bio":"Jupi","instrument":"Gitara","img":null}{"id":8,"name":"Andrija","surname":"Profesor","bio":null,"instrument":null,"img":null}


Thanks in advance.

Answer

First make sure you get the JSON as a response from the API by using console.log(data) in the ajax success call.

Then you need to parse the received JSON using JSON.parse()

 $.ajax({
     type : 'GET',
     url : 'api/v1/get_profesors.php',
     success : function(data){
         var data = JSON.parse(data);
         var content = 'Name : '+data.name ;
         content += ' Surname : '+data.surname ;
         content += ' Bio : '+data.bio ;
         content += ' Instrument : '+data.instrument ;
         $("#profesori").append(content);
     }
});
Comments