0

I am trying to set up a simple search function with Google Books API. When I have my search parameter set as a simple preset string, it works fine. But when I attempt to make it take user input for the search parameter using document.getElementByID, it suddenly no longer works. I am uncertain of what could be going wrong,

<!DOCTYPE html>

<html>
<head>
    <title>Google Books Search</title>
    <script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
</head>
<body>
<h1 id="title"></h1>
<h2>Searched "jquery"; Total results: <span id="total"></span>

<p>The results from 30 to 45 are displayed here (15 per page; results page #3).</p></h2>
<div id="results" style="display: flex; flex-wrap: wrap;"></div>
<input id="searchterm" type="text" placeholder="Search..." >
<button onclick="booksearch()">Search</button> 
<script>
    $(function booksearch(){
        let term = "document.getElementById("searchterm").value;"
        var parameter="?q="+term+"&startIndex=30&maxResults=15"; 
        var service_point="https://www.googleapis.com/books/v1/volumes/"+parameter;
        $.getJSON(service_point, function (json)
        {
            console.log(json);
            var total=json.totalItems;
            $("#total").text(total); 
            
            var resultHTML="";
            for (i in json.items)
            {
                var booktitle=json.items[i].volumeInfo.title;
                var bookid=json.items[i].id;
                var cover="";
                if (json.items[i].volumeInfo.imageLinks != null)
                    cover=json.items[i].volumeInfo.imageLinks.smallThumbnail;

                resultHTML+="<div class='bookdiv'>";
                resultHTML+="<img src='"+cover+"' style='float: left' />";
                resultHTML+="<a href='bookinfo.html?id="+bookid+"'>"+booktitle+"</a>";
                resultHTML+="</div>";
            }
            $("#results").html(resultHTML); 
            $(".bookdiv").css("width", "300px");
        });
    });
</script>

</body>
</html>

1 Answers1

0

You should not put your "document.getElementById("searchterm").value;" within quotes otherwise it will just be a string.

Use let term = document.getElementById("searchterm").value; instead.

On another note: I would suggest you use fetch() together with URLSearchParams which will do the "heavy-lifting" (i.e. URL-encoding, addition of ? and & etc.) for you instead of concatenating those strings yourself (and you will use some modern JavaScript).

See this SO answer for an example.

Mushroomator
  • 6,516
  • 1
  • 10
  • 27