0

The idea is to take a JSON array, loop through each of the entries for planets and output them to an unordered list, with one entry per li. All works well in this instance.

I have successfully written a method to output nested JSON when the JavaScript file contains the JSON array and the code below it, but I am having serious trouble identifying a method to retrieve the same data from an external .json file, using AJAX.

Here is the working local version.

<ul id="object-list"></ul>
$(document).ready( function() {
    var sol_sys = [];
    sol_sys = {
        "stars": [
            { "name": "Sun", "object": "Star", "url": "stars/sun" }
        ],
        "planets": [
            { "name": "Mercury", "object": "Planet", "parent": "Sun", "url": "planets/mercury" },
            { "name": "Venus", "object": "Planet", "parent": "Sun", "url": "planets/venus" },
            { "name": "Earth", "object": "Planet", "parent": "Sun", "url": "planets/earth" },
            { "name": "Mars", "object": "Planet", "parent": "Sun", "url": "planets/mars" },
            { "name": "Ceres", "object": "Dwarf Planet", "parent": "Sun", "url": "planets/ceres" },
            { "name": "Jupiter", "object": "Planet", "parent": "Sun", "url": "planets/jupiter" },
            { "name": "Saturn", "object": "Planet", "parent": "Sun", "url": "planets/saturn" },
            { "name": "Uranus", "object": "Planet", "parent": "Sun", "url": "planets/uranus" },
            { "name": "Neptune", "object": "Planet", "parent": "Sun", "url": "planets/neptune" },
            { "name": "Pluto", "object": "Dwarf Planet", "parent": "Sun", "url": "planets/pluto" },
            { "name": "Eris", "object": "Dwarf Planet", "parent": "Sun", "url": "planets/eris" }
        ],
        "moons": [
            { "name": "Luna", "object": "Moon", "parent": "Earth", "url": "moons/luna" },
            { "name": "Callisto", "object": "Moon", "parent": "Jupiter", "url": "moons/callisto" },
            { "name": "Ganymede", "object": "Moon", "parent": "Jupiter", "url": "moons/ganymede" },
            { "name": "Io", "object": "Moon", "parent": "Jupiter", "url": "moons/io" },
            { "name": "Europa", "object": "Moon", "parent": "Jupiter", "url": "moons/europa" },
            { "name": "Enceladus", "object": "Moon", "parent": "Saturn", "url": "moons/enceladus" },
            { "name": "Titan", "object": "Moon", "parent": "Saturn", "url": "moons/titan" },
            { "name": "Miranda", "object": "Moon", "parent": "Uranus", "url": "moons/miranda" },
            { "name": "Triton", "object": "Moon", "parent": "Neptune", "url": "moons/triton" },
            { "name": "Charon", "object": "Moon", "parent": "Pluto", "url": "moons/charon" }
        ]
    }

    var x = [];
    $.each(sol_sys.planets, function(index) {
        x += '<li><a href="' + sol_sys.planets[index].url + '" title="' + sol_sys.planets[index].name + '" target="_blank">' + sol_sys.planets[index].name + '</a></li>';
    });
    $('#object-list').append(x);
});

However, I have spent the past two days trying to figure out the method to achieve this, with the JSON kept separate in a separate .json file.

Here is an example of one method I have tried:

$(document).ready( function() {
    var sol_sys = $.getJSON('assets/data.json');
    var x = [];

    $.each(sol_sys.planets, function(index) {
        x += '<li><a href="' + sol_sys.planets[index].url + '" title="' + sol_sys.planets[index].name + '" target="_blank">' + sol_sys.planets[index].name + '</a></li>';
    });
    $('#object-list').append(x);
});

This code successfully fetches the data as can be seen in the console, but it also spits out this error message: Uncaught TypeError: Cannot read property 'length' of undefined

I am thinking that there is something obvious that I have completely missed. I have also tried the method demonstrated here, with exactly the same outcome.

Can anybody point me in the right direction?

Thanks!

DylRicho
  • 895
  • 1
  • 10
  • 25
  • Hi @DmitryS., I'm not sure what you mean exactly? – DylRicho Feb 15 '19 at 19:27
  • You described the above code fetches the data successfully using ajax as you see in the console. Can you show that console result? It seems `sol_sys.planets` is not an array. – Dmitry S. Feb 15 '19 at 19:35
  • @DmitryS. I think I mixed up some testing that I was doing in the console, pasting the `var sol_sys` line in there directly. I have tried so many things, I lost track. Sorry about that. It definitely does not work. – DylRicho Feb 15 '19 at 19:38
  • So, what the result do you get using `$.getJSON('assets/data.json')`? Can you provide a result of `console.log(sol_sys)` after you fetch data? – Dmitry S. Feb 15 '19 at 19:40
  • Possible duplicate of [jQuery getJSON save result into variable](https://stackoverflow.com/questions/15764844/jquery-getjson-save-result-into-variable) – Heretic Monkey Feb 15 '19 at 19:43
  • @DmitryS. By that, I simply meant that under `responseText` I see the array and its data, after declaring the variable and then calling it directly below in the console. – DylRicho Feb 15 '19 at 19:47
  • @DmitryS. - it's simply an async issue - you can't return from a call like that. – tymeJV Feb 15 '19 at 19:52
  • Use the success callback as explained [here](https://api.jquery.com/jquery.getjson/) to process the results you got from the server. – James Feb 15 '19 at 20:07
  • @tymeJV I think there is something else as well because your answer doesn't appear to be working. – DylRicho Feb 15 '19 at 20:08
  • @James I have followed that example. Just one of the many things I tried. – DylRicho Feb 15 '19 at 20:08
  • @DylRicho - If you open your console and check the network tab - you should see your call being made to `'assets/data.json'` - is it successful or erroring? – tymeJV Feb 15 '19 at 20:27
  • @tymeJV Yep, it is successful. HTTP status code 200. – DylRicho Feb 15 '19 at 20:29
  • OK, but you didn't show the code of you following that example, and that is the *only way* to make this work. So, I would go back to that model and ask a new question if you experience trouble. – James Feb 15 '19 at 21:19
  • @James I'm sorry that I haven't included everything. I have tried more methods than I can remember over the past two days, and Windows Update doing its thing while I was asleep didn't help either. I had a text file of the code that I had tried. That was lost. I think the part from that example that I'm stuck on, is how would I apply that to a nested array like the one I have? There is no example for nested arrays. – DylRicho Feb 15 '19 at 21:22

2 Answers2

2

$.getJSON is an async call - so you need to use the callback function to access the returned data:

$.getJSON('assets/data.json', function(sol_sys) {
    var x = [];

    $.each(sol_sys.planets, function(index) {
        x += '<li><a href="' + sol_sys.planets[index].url + '" title="' + sol_sys.planets[index].name + '" target="_blank">' + sol_sys.planets[index].name + '</a></li>';
    });
    $('#object-list').append(x);
});
tymeJV
  • 103,943
  • 14
  • 161
  • 157
  • Hello, thank you for your answer. I copied your code over directly, and it still doesn't appear to be working. – DylRicho Feb 15 '19 at 20:00
  • Turns out the JSON was incorrectly formatted. Your solution now works too. My bad. Thank you. :) – DylRicho Feb 15 '19 at 23:15
1

Hi you can do it this way:

your ajax:

function getList() {
   return $.ajax({
        type: "GET",
        url: "YourUrl"
    })

}

call it like this:

    getList().done(function(response){
    var data=JSON.parse(response);
    if (data != null) {
    jQuery.each(data, function(index, value){
//use an id in your ul in order to append some items
    $("#yourUl id").append('<li><a href=' + value.url+ '>' + value.name+ '</a></li>');
                                                    });
        }

})

Or

$.getJSON( 'assets/data.json').done(function(response) {
    var data=JSON.parse(response);
    if (data != null) {
    jQuery.each(data, function(index, value){
    //use an id in your ul in order to append some items
    $("#yourUl id").append('<li><a href=' + value.url+ '>' + value.name+ '</a></li>');
});
}
})

Edit: append the elements like this:

        $.getJSON( 'data.json').done(function(response) {
    jQuery.each(response, function(index, value){
    $("#planetList").append('<li>'+index+'</li>');
     jQuery.each(value, function(index2, value2){
    $("#planetList").append('<ul><li><a href=' +value2.url+ '>' +value2.name+ '</a></li>')
    console.log(value2);
     })
         $("#planetList").append('<ul>');
    })
})

Hope it helps

stan chacon
  • 768
  • 1
  • 6
  • 19
  • Hi Stan, I appreciate your answer. Your first method seems to provide the same result as the above answer (`.json` file is successfully loaded, but there is no visual output in HTML). I appended `dataType: "text"` to the function `getList()` and that resolved the `statusText: "parseerror"` that I was getting. – DylRicho Feb 15 '19 at 20:54
  • Now I'm left with a different problem, which is something I encountered last night while trying to debug. Here is the new error with that fix in place: `Uncaught SyntaxError: Unexpected token s in JSON at position 0`. – DylRicho Feb 15 '19 at 20:54
  • 1
    @DylRicho can you log the response and post a picture of that ? – stan chacon Feb 15 '19 at 20:55
  • 1
    @DylRicho i will try to do this on my pc and give you an update – stan chacon Feb 15 '19 at 20:56
  • 1
    @DylRicho i have edited the post check is the answer helps – stan chacon Feb 15 '19 at 21:43
  • Still the same outcome, sadly. :( – DylRicho Feb 15 '19 at 21:57
  • 1
    @DylRicho the json you get where it comes from ? is an array generated from some database or is static array in some js file? cause i use your json and it create the list https://imgur.com/a/iG9xw1Q – stan chacon Feb 15 '19 at 22:01
  • 1
    @dyl i just added a picture from the result i get – stan chacon Feb 15 '19 at 22:06
  • Oh, I see what you mean now. The array is generated from a static `.json` file. – DylRicho Feb 15 '19 at 22:10
  • Your edit also doesn't appear to work. I honestly don't know why nothing is working. – DylRicho Feb 15 '19 at 22:15
  • 1
    @DylRicho here is the script picture https://imgur.com/a/Lb1q07M, and here the html picture https://imgur.com/a/KAJQEXu, also the display https://imgur.com/a/rOzkA8D try to do it like that – stan chacon Feb 15 '19 at 22:19
  • 1
    @DylRicho your json need to looks like this and nothing else https://imgur.com/a/dFQME2Z – stan chacon Feb 15 '19 at 23:01
  • Thank you so much! I was almost ready to give up. This has been a headache for the past two days. Seriously, thank you! – DylRicho Feb 15 '19 at 23:04
  • I appreciate your incredible patience. :) – DylRicho Feb 15 '19 at 23:07