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

A step-by-step guide on how to refresh a circular loading indicator

I have been researching how to create a circular progress bar using canvas, and I came across this code. After making some modifications to the code snippets that I found online, I encountered an issue - I can't seem to reload the circular path once i ...

Issue with Discord.js voice connection destruction函数

I've been attempting to implement a "Stop" command using the @discordjs/voice package, but I'm encountering an error. Despite my efforts to add some error handling, the issue persists. Below is the code snippet: async function stop(message) { t ...

What is the recommended dispatch_async method for populating a table view controller with JSON data?

I have some JSON data that I need to display in a table view. What is the best approach for fetching and loading this data in the background using dispatch methods or child threads? ...

Securing routes with passport.js in a MEAN Stack setting

I am facing an issue with securing individual routes in my admin panel using passport.js. The user signup functionality is working fine, and I am able to login successfully. However, the req.isAuthenticated() function always returns false, preventing me fr ...

Attempting to submit a form to Mailchimp with Vue.js and Axios causes a CORS error to occur

In my Vue.js application, I have a feature that sends email data from a form to Mailchimp using the Axios library. I recently learned that in order to bypass CORS restrictions when posting to Mailchimp's URL, I need to use the post-json version and a ...

How can we enforce that the input consists of digits first, followed by a space, and then

Can regex (with javascript possibly) be used to mandate numbers, followed by a space, and then letters? I'm a bit lost on where to start with this... I understand that using an HTML5 pattern would work for this... [0-9]+[ ][a-zA-Z0-9]+ However, I ...

`The value of an element within an array changes automatically`

In my current setup, I have a traditional array where each element represents an HTML element. The issue arises when I manipulate these elements within the array; any changes made to the HTML element also reflect in the array automatically. However, I pref ...

Implement the maskmoney library in your input fields

In the form below, I am automatically adding inputs using a JavaScript function like this: $('.Preco1').maskMoney({ decimal: '.', thousands: ' ', precision: 2 }); $('.Preco1').focus(); $('#sub').maskMon ...

Style the labels on the axis of Frappe Charts with colors (potentially utilizing the appropriate CSS selector)

Is it possible to style the x and y axis labels in a Frappe chart with different colors? https://i.stack.imgur.com/A3vUq.png While trying to identify the CSS selectors using Chrome DevTools, I found that a single text element (representing an x axis labe ...

What is the best way to interact with Redis without using any external modules?

I am curious about the communication process between the node redis wrapper and the RESP (REdis Serialization Protocol) database. Here is a simple example: const redis = function(uri) { this.client = '' // How do we establish a connection wit ...

What is the process of connecting a Yarn module to a Docker container in another repository?

I'm currently facing a challenge in linking a module to a Docker container from another repository. To provide some background, I have a container hosting a React application named launch-control-admin. This project relies on a yarn module called @com ...

Error in AngularJS - filterProvider not recognized

When the two script statements below are combined, they cause an error: "Error: [$injector:unpr] Unknown provider: searchNameFilterProvider <- searchNameFilter." Can someone explain why this happens? 1st segment Find Person: <input type="text" ng-m ...

I am encountering an issue stating "indexRouter has not been defined"

Encountering an error "indexRouter is not defined" while attempting to run the code below. Despite attempts to remove the line, additional errors persist. Can anyone clarify the rationale behind using the common variable router for both index.js and user.j ...

What is the proper way to add an object to an array within an object in TypeScript?

import {Schedule} from './schedule.model'; export class ScheduleService{ private schedules:Schedule[]=[ new Schedule("5:00","reading"), new Schedule("6:00","writing"), new Schedule("7:00","cleaning") ]; getSchedule(){ ret ...

How to Break Free from JQuery AJAX Result while Preserving its True Worth

Is it possible to display the exact value <script>alert('test');</script> inside my div tag if the return result is <script>alert('test');</script>? $.ajax({ url:'${pageContext.request.c ...

Uploading files with the help of Formik and the Material-UI stepper component

When attempting to upload a file, the entire component refreshes each time. The process involves 3 steps: the first step captures the user's name, the second step collects their address, and the third step allows them to upload a profile picture. Howe ...

Performing a series of get requests in Angular 2

There is a configuration service that retrieves specific information from a JSON file. getConfiguration(key) { return this.http.get('./app/config/development.json').map(res => { this.result = res.json(); return this.result[ke ...

Experiencing an unexpected wait before the requestAnimationFrame?

Surprisingly, Internet Explorer is actually performing the way I want it to in this case :-) I developed a function for SVG animations using requestAnimationFrame (for simplicity, I left out the value calculations here ... but my initial test involved an ...

Is there a way to determine if jQuery lightslider has been initialized, and if so, how can I effectively remove the instance?

Currently, I have integrated the JQuery lightSlider into my project. Despite some code adjustments, it is functioning well. My goal is to dynamically replace the lightSlider content with data returned via AJAX, which I have successfully achieved. After r ...

What is the most effective method to convert PHP data into JSON and present it in the jQuery success scenario?

In the realm of jQuery, I have this particular piece of code: <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script> <script type="text/javascript" > $(function() { $("input[type ...