Deadpool
Deadpool

Reputation: 8240

$.ajax() printing an array of jsonObjects not getting printed

I have an array of json Objects that are to be retrieved by $.ajax() and printed in a table. But, I cannot print though they are getting retrieved by Webpage through XAMPP (Seen in Network >> xhr). Can someone help?

JSON:

{"people":[
    {"firstName":"Peter","lastName":"De'Souza","blogURL":"www.google.com"},
    {"firstName":"Romeo","lastName":"Cherolov","blogURL":"www.google.com"},
    {"firstName":"Caspian","lastName":"Monovola","blogURL":"www.google.com"}
    {"firstName":"Sita","lastName":"Martin","blogURL":"www.google.com"}
    {"firstName":"Rina","lastName":"Schenoi","blogURL":"www.google.com"}
]}

jQuery:

$.ajax({
      type: 'POST',
      url: 'http://localhost/example4/data.json',
      data: { patientID: "1" },
      contentType: 'application/json; charset=utf-8',
      dataType: 'json',
      success: function(jsonData) {

            for (i=0;i<5;i++)
            {
                console.log(jsonData[i].firstName);
            }

      },
      error: function() {
        alert('Some Error');
      }
});  

It is just throwing the Error Alert, though in Network >> xhr I can see the 'people - array of json objects' being fetched. Pls help!

Upvotes: 1

Views: 45

Answers (2)

M3ghana
M3ghana

Reputation: 1271

Modify your loop as

foreach(jsonData.people as val)
 {
       console.log(val['firstName']);
 }

Upvotes: 0

Joy Biswas
Joy Biswas

Reputation: 6527

try console.log(jsonData.people[i].firstName);

Upvotes: 2

Related Questions