Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript Asynchronous Programming with JavaScript Asynchronous JavaScript with Callbacks Implement a Callback

John Norris
John Norris
20,859 Points

Uncaught TypeError: callback is not a function at XMLHttpRequest.xhr.onload | callbacks.js:13

I receive the following error in the console when I click the button. I cannot figure out why. Please help. Thank you!

Uncaught TypeError: callback is not a function at XMLHttpRequest.xhr.onload | callbacks.js:13
const astrosUrl = 'http://api.open-notify.org/astros.json';
const wikiUrl = 'https://en.wikipedia.org/api/rest_v1/page/summary/';
const peopleList = document.getElementById('people');
const btn = document.querySelector('button');

// Make an AJAX request
function getJSON(url, callback) {
  const xhr = new XMLHttpRequest();
  xhr.open('GET', url);
  xhr.onload = () => {
    if(xhr.status === 200) {
      let data = JSON.parse(xhr.responseText);
      return callback(data); // Line 13
    }
  };
  xhr.send();
}

// Generate the markup for each profile
function generateHTML(data) {
  const section = document.createElement('section');
  peopleList.appendChild(section);
  section.innerHTML = `
    <img src=${data.thumbnail.source}>
    <h2>${data.title}</h2>
    <p>${data.description}</p>
    <p>${data.extract}</p>
  `;
}

//getJSON(astrosUrl);

btn.addEventListener('click', () => {
  getJSON(astrosUrl), (json) => {
    json.people.map( person => {
      getJSON(wikiUrl + person.name, generateHTML);
    });
  };
event.target.remove();
});

1 Answer

You have a couple of parentheses that need to be fixed in btn.addEventListener:

btn.addEventListener('click', () => {
  getJSON(astrosUrl), (json) => {
    json.people.map( person => {
      getJSON(wikiUrl + person.name, generateHTML);
    });
  };
event.target.remove();
});

There shouldn't be a closing parenthesis after astrosUrl here:

getJSON(astrosUrl), (json) => {

This leaves callback in getJSON() undefined - the cause of the error you receive.

There should be a closing parenthesis after } here:

  };
event.target.remove();