Search code examples
javascriptjqueryjsonjsonp

for each, item[i].id isnt working. any ideas?


Done this before in the past. But having issues with this again

Trying to get the ids from a fb page using the api from fb

Here is an example of the outputted json.

{
  "data": [
    {
      "created_time": "2019-01-10T05:50:49+0000",
      "message": "hello world",
      "id": "233542"
    },
    {
      "created_time": "2019-01-10T05:50:48+0000",
      "message": "hello world",
      "id": "454524"
    },
    {
      "created_time": "2018-12-24T06:19:31+0000",
      "message": "hello world",
      "id": "399434"
    }
    ]
}

Script

var key = "(insert fb api here)";

 <!-- facebook api get -->
                var getkey = "https://graph.facebook.com/v3.2/(insert fb id here)/feed?access_token=" + key;

        $.ajax({
          type: 'GET',
          url: (getkey),
          contentType: 'application/json',
          dataType:'jsonp',
          responseType:'application/json',
          xhrFields: {
            withCredentials: true
          },
          headers: {
            'Access-Control-Allow-Credentials' : true,
            'Access-Control-Allow-Origin':'*',
            'Access-Control-Allow-Methods':'GET',
            'Access-Control-Allow-Headers':'application/json',
          },
          success: function(data) {

              $.each(data, function (i, item) {

                console.log(item[i].id);



            });
          },
          error: function(error) {

            console.log("error");
          }
});

one way iv found that works is

console.log(item[0].id);

How ever this just console logs the first of the nested json, Am I missing something?

Any help is appreciated.


Solution

  • try this :

    $.each(data.data, function (i, item) {
         console.log(item.id);
    });