1

I'm new to JavaScript, and as an exercise, I'm trying to combine two snippets of code I found online.

I want to prompt the user for a keyword, call a list of books about the keyword from the Google books API, and print the list.

<html>
  <head>
  </head>
  <body>
    <div id="content"></div>

<p id="demo"></p>

<script>

    function myFunction() {
    var person = prompt("enter a keyword", "keyword");
    if (person != null) {
        var url="https://www.googleapis.com/books/v1/volumes?q=" + person;
        document.write(url);
        document.write(person);
        var xhttp = new XMLHttpRequest();
        xhttp.open("GET", url, false);
        xhttp.send();
        var obj = JSON.parse(xhttp.responseText);
        document.getElementById("demo").innerHTML = obj.item.volumeInfo.title;
        document.write("done")
    }
}


</script>   

  <button onclick="myFunction()">Try it</button>

  </body>
</html>

I added various document.write() statements to test how far the function gets. I can only get it past writing the url and keyword. It never gets to "done" at the end.

Both snippets of code worked before I combined them.

Anyone see what I'm doing wrong?

bdkopen
  • 494
  • 1
  • 6
  • 16
litmuz
  • 71
  • 8
  • 3
    Don't use `document.write()` after the page is done loading. Open your developer console to see errors. –  May 12 '17 at 00:56
  • 2
    to expand on that, document.write is likely to cause errors – Jaromanda X May 12 '17 at 01:00
  • 1
    [Here's a demo](https://jsfiddle.net/rukfg7d3/) that may help. Notice that I update the content of the `demo` element instead of using `document.write()`. Also, your `obj.item.volumeInfo.title` won't work because there is no `item` property, though there is an `items`, which points to an Array of Objects. The demo prints the full response so you can examine it. –  May 12 '17 at 01:05
  • 1
    [Here's an updated demo](https://jsfiddle.net/rukfg7d3/1/) that iterates the Array I mentioned above and prints the `.volumeInfo.title` of each item. –  May 12 '17 at 01:07
  • 2
    ...also note that sending a *"synchronous"* request isn't a great approach. Works for the demo, but don't do it in practice. –  May 12 '17 at 01:08
  • 1
    Synchronous requests in browsers are deprecated; AJAX requests are usually asynchronous. Usually you would add a callback to the `onreadystatechange` event. See the answer to http://stackoverflow.com/questions/8567114 – david25272 May 12 '17 at 01:11

0 Answers0