0

I am trying to use the New York Times bestseller list API to list the current top 20 in html - I've managed to retrieve the data using ajax (I can see it using developer tools) but have got stuck trying to get it to display on the page. I don't get any error messages - nothing happens. This is my code as is:

<!DOCTYPE HTML>
<html>

    <head>
        <title>Discover Books</title>
        <link rel="stylesheet" type="text/css" href="stylesheet.css">
        <meta charset="UTF-8">
        <script type="text/javascript" src="http://code.jquery.com/jquery-1.11.3.js"></script>

    <div id='books'> 
    </div>


    </head>

<script>
    $(document).ready(function(){
    $.ajax ({
            type: 'GET',
        dataType: 'json',
        url: 'http://api.nytimes.com/svc/books/v3/lists/hardcover-fiction?api-key=*API_KEY*',

        success: function(response){
          console.log(response);
          for(var i = 0; i < response.length; i++) {
            var listing = response[i];
            $('#books').append('<h3>' + title + '</h3>');
          }
      }, 
        error: function(xhr, status, error){
          console.log(status);
          console.log(error);
      }
    });
  })
</script>

</html>

Any hints as to what I'm doing wrong? Thanks

2
  • Does it default to the error function? Commented Jan 5, 2016 at 23:36
  • 1
    Don't put your api key in the code example. I don't know how this API works, but its generally a bad idea. Commented Jan 5, 2016 at 23:39

2 Answers 2

1

title is undefined in you success function. You should refer to listing.title.

success: function(response){
  console.log(response);
  for(var i = 0; i < response.length; i++) {
    var listing = response[i];
    $('#books').append('<h3>' + listing.title + '</h3>');
  }
}

And looking at the API response, you need to drill down into the JSON a bit to get to the books.

success: function(response){
  console.log(response);
  books = response.results.books; //You may need to tinker with this
  for(var i = 0; i < books.length; i++) {
    var listing = books[i];
    $('#books').append('<h3>' + listing.title + '</h3>');
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much that's solved the problem! I've been stuck on that for hours...
Hey, if you are paying for that api key or you are concerned with its security at all, you may want to request a new one.
0

Don't you have to call JSON.parse(response) before using its elements?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.