The Google Books API initially displays only 10 results. To ensure that all results are shown, we can implement iteration to increment the startIndex until all results have

function bookSearch() {
  var search = document.getElementById('search').value
  document.getElementById('results').innerHTML = ""
  console.log(search)
  var startIndex =

I have a requirement to continuously make Ajax calls to display all the items instead of just the first 10. By using the maxresults parameter, we can fetch 40 items at a time. This requires updating the startIndex value from 0 to 20 to 40 and so on after each iteration.

while (startIndex < 2000) {
  $.ajax({
    url: "https://www.googleapis.com/books/v1/volumes?q=" + search + "&startIndex=" + startIndex + "&maxResults=40",
    dataType: "json",

    success: function (data) {
      console.log(data)
      for (i = 0; i < data.items.length; i++) {
        results.innerHTML += "<h2>" + data.items[i].volumeInfo.title + "</h2>"
        results.innerHTML += "<h2>" + data.items[i].volumeInfo.authors + "</h2>"
        results.innerHTML += "<h2>" + data.items[i].volumeInfo.publishedDate + "</h2>"
      }
    },
    type: 'GET'
  });
}
}

document.getElementById('button').addEventListener('click', bookSearch, false)

Answer №1

If you want to display search results starting from an initial point until it exceeds 40 items, you can utilize the following code:

// Start with startIndex set as 0
var startIndex=0;

// When button is clicked
$("#button").click(function(){
  $("#results").html('<img src="img/loader.gif" alt="" class="loader">');
  var searchInput = $("#search").val();
  getBooks(searchInput)
})

// Run function on click
function getBooks(search) {
  RunApi(search, startIndex);
  $("#results img").remove();
}

// Function to fetch results through API call
function RunApi(search, start){
  $.ajax({
    url:"https://www.googleapis.com/books/v1/volumes?q=" + search + "&maxResults=40&startIndex="+start,
    dataType: "json",

    success: function(data) {
      console.log(data)
      totalItems = data.totalItems;
      if(data.items){
        for(i=0; i<data.items.length; i++){
          if(data.items[i].volumeInfo){
            var itemNubmer = startIndex+i;
            results.innerHTML += "<h2>"+itemNubmer+": " + data.items[i].volumeInfo.title + "</h2>"
            // Add more details if needed
          }
          
        }
      }
      // Call the function recursively if there are more than 40 total items
      if(totalItems > 40){
      startIndex+=40;
      RunApi(search, startIndex);
      }
    },
    type:'GET'
  });
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encounter error message "Angular-CLI: Karma-Webpack fails due to 'file or directory not found'"

After initially starting with the classic Angular/systemjs setup for the Tour of Heroes, I transitioned to using angular-client. The application now performs well in both development and production modes, except for when I try to run tests using ng test. A ...

Animating with JavaScript

I have a members button on my website that triggers a dropdown animation when clicked. However, the issue is that the animation occurs every time a page is loaded, even if the button is not clicked. I want the dropdown to only open when the button is click ...

Tips for creating a div element that closes on the second click:

On the PC version, I have three blocks that open and close perfectly when clicked. However, on the mobile version, when I click on one block, it opens but does not close unless I click on another block. Additionally, if I click again on the same block th ...

Change the names of embedded entities during the Jolt conversion process

I have successfully converted one JSON object to another JSON object, everything looks good. However, there is one scenario that is not working as expected. Initial JSON: { "v1": 1, "v2": { "inv1": { "Id&qu ...

Show the React component once the typewriter effect animation is complete

Hello there, I am looking to showcase my social links once the Typewriter effect finishes typing out a sentence in TypeScript. As someone new to React, I'm not quite sure how to make it happen though. Take a look at the code snippet below: ` import ...

Error: You are not able to utilize an import statement outside of a module when utilizing the `fast-image-zoom` feature

Currently, I am attempting to integrate fast-image-zoom into my React/Next.js application and unfortunately encountering an error message that reads: SyntaxError: Cannot use import statement outside a module at Object.compileFunction (node:vm:353:18) ...

Ways to stop a JS plugin affecting HTML anchors and preventing them from automatically scrolling to the top

My friend is working on a website and he's using a plugin called Flip Lightbox. The basic functionality of the plugin is that when you click on an image, it flips over and pops out as a lightbox. Everything works fine, however, if you scroll down the ...

`Count the number of rows needed to accommodate text line breaks within a div element`

Is there a method to determine the number of lines that text breaks into using the CSS property word-break: break-all? For example, if I have a div like this: <div>Sample text to check how many lines the text is broken into</div> And the corr ...

Hold off on running the code until the image from the AJAX request is fully loaded and

Currently, I am facing a challenge with my code that aims to determine the width and height of a div only after it has been loaded with an image from an AJAX request. The dimensions of the div remain 0x0 until the image is successfully placed inside it, c ...

Unlocking Node.js packages within React JS is a seamless process

Currently, I am developing a React Serverless App with AWS. I am looking for ways to incorporate a Node JS specific package into the React JS code without requiring Node JS on the backend. One package that I need access to is font-list, which enables list ...

Iterate through the object received from the node promise and pass it to the subsequent .then method

After grappling with this issue for what feels like an eternity, I find myself immersed in learning about Node.js and trying to grasp the concept of promises. My current challenge involves retrieving data from the Spotify API, starting with fetching my ow ...

Adjusting HTML5 drag height while resizing the window

Code conundrum: var dragHeight = window.innerHeight - parseInt(jQuery("#drag_area").css("margin-top")) - 5;. It sets the drag height based on browser size, but there's a glitch. If I start with a non-maximized browser and then maximize it, the drag he ...

Is there a way for me to retrieve the list values sent back by the controller through ajax?

How do I access values in a list returned from my controller using AJAX? I keep getting undefined when trying to display an alert. Controller @ResponseBody @RequestMapping(value="/practice/{category}/option", method = RequestMethod.POST, produces = "appl ...

Tips for preserving both existing data and new data within React's useState hook in React Native or ReactJS?

As I dive into learning reactjs, one question that has been on my mind is how to store both previous and upcoming data in useState. Is there a special trick for achieving this? For example: Imagine I enter "A" and then follow it with "B". My goal is to ha ...

The event that occurred on the DOM during the AJAX upload process within the Drupal file module

One of the great features of Drupal is its built-in ajax framework. This allows developers to easily write callback functions like the one below: $commands = array(); $commands[] = ajax_command_replace(NULL, theme('status_messages')); return arr ...

Encountering trouble with displaying data in Express and Mongoose

Struggling to comprehend how to define and utilize an API in Express, while using Mongoose to connect with MongoDB. Successfully saving objects from input on the front end, but getting lost when it comes to retrieving and displaying the saved data. Take a ...

Clearing Out a Shopping Cart in Angular

Hey there, I have a little dilemma with my shopping cart system. I can easily add and delete products using an API. However, when it comes to deleting an item from the cart, I have to do it one by one by clicking on a button for each item, which is not ver ...

Is there an easy method to verify if the local storage is devoid of any data?

Query is named aptly; seeking to verify in a conditional statement. ...

Tracking your daily nutrition using cronometer with the powerful combination of JavaScript

I'm currently developing a JavaScript cronometer in vueJS. I want the timer to start at 5 minutes (300 seconds) and then continue counting minutes and seconds. Although my cronometer is functioning, I am struggling to get it to start counting minutes ...

Transform a date string into a date entity

Collecting the user's input for the date and saving it as a string variable. The format of the value is Fri Aug 27 2021 00:00:00 GMT+0530 (India Standard Time) My goal is to convert this string back into a new Date() object in order to make additiona ...