0

I'm learning how to access an array of JSON objects using AJAX but can't seem to access my data. I keep getting undefined when trying to access a certain value of object in the array. I know I have the data there as when I called console.log I got the result in the picture below...

I'm trying to get the first object in the array and get it's name value using this code...

$('document').ready(function(){
$.ajax({
    type: "POST",
    url: "web_services/cow/api.php",
    data: "{ rating: 4.7}",
    contentType: "application/json; charset=utf-8",
    cache : false,
    dataType: "json",
    success: function(data) {
        console.log(data[0]['name']);
    },
    error: function(){
       alert("There was an error loggin in");
    }
});
});

But I only get undefined unfortunately. Would the way I'm implementing this be okay or is there a better way?

Result of console.log

Thank you very much for any help and taking the time to read my question.

SmiffyKmc
  • 801
  • 1
  • 16
  • 34
  • 1
    try `data.data[0]['name']` – Pranav C Balan Jun 21 '16 at 17:11
  • 1
    You have objects, not JSON. JSON is a data format (think of a text file) that can be converted into objects and arrays. If `data` is the object you've got in the image, then you can access it at `data.data[0].name`. You've got a bunch of nested objects and arrays. – Mike Cluck Jun 21 '16 at 17:12
  • Thanks guys that worked for me. Couldn't think why it wasn't working. Is the way I'm doing it incorrect? Want to make sure I know the right way to have this. – SmiffyKmc Jun 21 '16 at 17:15
  • 1
    @SmiffyKmc It wasn't working before because you were accessing it incorrectly. Not much more to say on that. – Mike Cluck Jun 21 '16 at 17:16
  • @MikeC Cool! I guess it's the data's data array I'm accessing! Thanks very much everyone! – SmiffyKmc Jun 21 '16 at 17:20

0 Answers0