-1

I try to get a JSON file on my local host but on console I receive an array with my all objects from data.json but I receive the following error

Uncaught TypeError: Cannot read property 'forEach' of undefined

This is my code:

$.ajax({
        type : 'GET',
        dataType : 'json',
        url: 'http://localhost:8888/data/folder/data.json',
        success : function(data) {
            console.log(data); 
        var data =[];
        var covers = document.getElementById("covers");
        var blockTemplate = covers.getElementsByTagName("div")[0].cloneNode(true);
        covers.getElementsByTagName("div")[0].remove();
        data.info.forEach( function(obj) {
            block = blockTemplate.cloneNode(true);
            block.getElementsByTagName("a")[0].setAttribute('href', obj.link);
            block.getElementsByTagName("img")[0].setAttribute('src', obj.cover);
            covers.appendChild(block);
        });
    }
    });

Any idea how can I solve this?

Markus Hayner
  • 2,869
  • 2
  • 28
  • 60

4 Answers4

2

Remove

var data =[];

From success().

This is overriding the ajax response.

Prasanna
  • 779
  • 5
  • 13
  • `info` is the name of my object which contain 6 arrays. then how is the way of grabbing that data? – Markus Hayner Jun 26 '15 at 12:25
  • @MarkusHayner Just remove `var data=[];`. You’re accessing `info` from an empty array which returns `undefined`. Then you’re trying to apply `forEach` on it. Because `undefined` has no properties, there’s also no `forEach` property on it, hence the error message. – Sebastian Simon Jun 26 '15 at 12:29
1

var data = data.info;
    data.forEach( function(obj) {
      block = blockTemplate.cloneNode(true);
      block.getElementsByTagName("a")[0].setAttribute('href', obj.link);
      block.getElementsByTagName("img")[0].setAttribute('src', obj.cover);
      covers.appendChild(block);
    });
Himesh Aadeshara
  • 2,114
  • 16
  • 26
0

Change success : function(data) { with success : function(response) { response in success and your data array is ambiguous. This will create problem. In javascript variables overrides when you'll define again.

Take a look here

What is the scope of variables in JavaScript?

Community
  • 1
  • 1
Kaushik
  • 2,072
  • 1
  • 23
  • 31
-1

In your case I think that "info" object of "data" is not defined or not received from server.

You can also loop your json object as shown below :

if(typeof(data.info) != "undefined")
    for(i in data.info)
         {
                var obj = data.info[i];
                block = blockTemplate.cloneNode(true);
                block.getElementsByTagName("a")[0].setAttribute('href', obj.link);
                block.getElementsByTagName("img")[0].setAttribute('src', obj.cover);
                covers.appendChild(block);
         }
}
IBAD GORE
  • 403
  • 2
  • 5