It doesn't print the names on screen with fetch call

Filip Tomeski

i need help,i have to call the data from the given url with fetch call. It should print the name of academy in and student names in on screen but when i click the button nothing happens. I know maybe its a bit huge code and it takes time but i would be grateful if someone could help me. Thank you in advance :)

$(document).ready(function() {

function printStudents(responseStudents) {
    let h1Element = $(`<h1></h1>`).text(`${responseStudents.academy}`);
    let uList = $(`<ul></ul>`);

    $("body").append(h1Element, uList);
    for (i = 0; i < responseStudents.length; i++) {
        uList.append(`<li> ${responseStudents.students[i]}</li>`);
    }
}

$("#button").click(function () {
    
        fetch ("https://raw.githubusercontent.com/Drakso/AJS2019/master/Class1/students.json")
        .then (function (response) {
            return response.json();
        })
        .then (function (data) {
            //let responseStudents = JSON.parse(response);
            //printStudents(responseStudents);
            console.log(data)
            
        },).catch (function (error) {
            alert("USer not found");
        })
    })

})

Lakshya Thakur

Hey the following should work for you :-

You were trying to access length property of response (which I passed here as data) object instead of the students array so your loop was not running.

$(document).ready(function() {

function printStudents(data) {
    let h1Element = $(`<h1></h1>`).text(`${data.academy}`);
    let uList = $(`<ul></ul>`);
    let responseStudents = data.students;
    $("body").append(h1Element, uList);
    for (i = 0; i < responseStudents.length; i++) {
        uList.append(`<li> ${responseStudents[i]}</li>`);
    }
}

$("#button").click(function () {
    
        fetch ("https://raw.githubusercontent.com/Drakso/AJS2019/master/Class1/students.json")
        .then (function (response) {
            return response.json();
        })
        .then (function (data) {
            printStudents(data);
            
        },).catch (function (error) {
            alert("USer not found");
        })
    })
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button id = 'button'>Click me</button>

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related