Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Jeriah Bowers
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Jeriah Bowers
Front End Web Development Techdegree Graduate 20,590 Points

API Troubleshooting

Ok, so I'm in the 10th project on front end web development and I'm running into a problem with the Random User Generator API. It's displaying undefined above the information I have printed out on the page itself if you run it you'll see what I'm talking about I can't find anything on it. So any help is welcomed. I'm not including the CSS cause I don't see how that could affect it.

HTML

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>AJAX Project</title>
    <link rel="stylesheet" href="css/main.css">
</head>
<body>
<h1>Awesome Startup Employee Directory</h1>
    <div id="employeeList"></div>    

<script
  src="https://code.jquery.com/jquery-3.2.1.min.js"
  integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
  crossorigin="anonymous"></script>   
<script src="js/main.js"></script>    
</body>
</html>

JS

let html; 

$.ajax({
  url: 'https://randomuser.me/api/?results=5000',
  dataType: 'json',
  success: function(data) {
    html += "<ul>"
    for(i = 0; i < 12; i++) {
       html += "<li>";
       html += "<img src=" + '"' + data.results[i].picture.medium + '"' + ">";
       html += "<div id='main'>"
       html += "<h3>" + data.results[i].name.first + " " + data.results[i].name.last + "</h3>";
       html += "<p>" + data.results[i].email + "</p>";
       html += "<p>" + data.results[i].location.city + "</p>";
       html += "<p class='popup'>" + data.results[i].phone + "</p>"
       html += "<p class='popup'>" + data.results[i].location.street + ", " + data.results[i].location.state + " " + data.results[i].location.postcode + "</p>";
       html += "<p class='popup'>" + data.results[i].dob + "</p>"
       html += "</div>"
       html += "</li>";
    }   
      html += "</ul>"
      $("#employeeList").html(html);
  }
});

Thank-you.

1 Answer

That is because you are initializing 'html' but not assigning anything to it in the beginning. If you do:

let html = "";

Instead of

let html;

It should be solved.

This only happens because you do += to an unassigned variable before the for loop