A JSON request is being processed within a while loop

Attempting to complete what I initially thought was a simple task has led me to believe that I may have oversimplified the process or made a mistake in my loop. My objective is to browse through a series of links containing JSON objects in order to identify specific ones with particular data.

The JSON links under review have the following format:

Link 1:

{"genre": "fantasy", "title": "Book 1"}

Link 2:

{"genre": "scifi", "title": "Book 2"}

The aim of my loop is to locate a book categorized as 'scifi', however, my current code does not seem to produce any results. If anyone can pinpoint where I may have erred, your assistance would be greatly appreciated. As it may not be evident, I am relatively new to this, so I welcome any suggestions for improvement.

function find_book(){ // triggered by button onclick
    var i = curr_line+1 // initial value for current line is 0
    var x = 0;
    var limit = bookcount-1; // total number of books stored in bookcount variable

    while(x != 1) {
        request= new XMLHttpRequest();
        request.open("GET","http://example.com/books/?book="+i,true);                    
        request.onreadystatechange=function() {
            if(request.readyState==4 && request.status==200) {
                var jsonbook = JSON.parse(request.responseText);
                alert('genre is'+jsonbook.genre);
            }
        }
        request.send()

        if(jsonbook.genre == "scifi"){
            alert('book is at '+i);
            x=1;
        }
        if(i>limit){
            alert('end of book list');
            x=1;
        }

        i++;
    }
}

Answer №1

The idea of a JSON book is beyond the current discussion. Additionally, it's important to note that ajax calls are inherently asynchronous (hence the "a" in ajax). One way to approach this problem is by creating a simple recursive function like the one below:

function searchForBook(bookID, limit) {
    let request = new XMLHttpRequest();
    request.open("GET", "http://example.com/books/?book=" + bookID, true);
    request.onreadystatechange = function () {
        if (request.readyState == 4 && request.status == 200) {
            let jsonBook = JSON.parse(request.responseText);
            alert('The genre is' + jsonBook.genre);
            if (jsonBook.genre === "scifi") {
                alert('Found the book: ' + bookID);
                return;
            } else if (bookID > limit) {
                alert('Reached end of book list');
                return;
            } else {
                bookID++;
                searchForBook(bookID, limit)
            }
        }
    }
    request.send()
}

function findDesiredBook(){ // gets invoked on button click
    let startingLine = lineIndex+1; // default value for current line is 0
    let maximumLimit = totalNumberOfBooks-1; // total number of available books

    searchForBook(startingLine, maximumLimit);
}

Answer №2

One thing to note is moving the following code beneath your

alert('genre is'+jsonbook.genre);
statement.

if(jsonbook.genre == "scifi"){
 alert('book is at '+i);
 x=1;
 }

if(i>limit){
alert('end of book list');
x=1;
}

When the call is asynchronous, it's crucial that you process the jsonobject with your own logic once it returns. The updated code should resemble the example below:

   if(request.readyState==4 && request.status==200)
    {

       var jsonbook = JSON.parse(request.responseText);
       alert('genre is'+jsonbook.genre);
       if(jsonbook.genre == "scifi"){
         alert('book is at '+i);
         x=1;
       }

       if(i>limit){
           alert('end of book list');
            x=1;
       }
    }

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

The Android webview encountered an error: XMLHttpRequest failed to load because the specified Origin <url> is not permitted by Access-Control-Allow-Origin restrictions

I have developed an application that loads an entire website in an Android WebView. The native code in the Android project communicates with the webpage using the Android Jockey Library, and vice versa. Everything is working smoothly except for one instan ...

Adding a div to the preceding div based on matching IDs in AngularJS

Here is a representation of my layout in HTML: <div ng-repeat="message in messages"> <div ng-class="{'messages messages--sent': userId == message.id, 'messages messages--received': userId != me ...

What is the best way to shorten string values that exceed a certain length?

Here is an array list I have: $myarray = array( array( 'name' => 'File name 1 - type.zip', 'size' => '600KB', ), array( 'name' => 'File name 2 - type.pdf&a ...

guide on incorporating Google Maps in a Vue.js application

Can anyone help me with displaying a Google Map using Vue.js? I have provided the code below, but I keep getting an error saying "maps is undefined" even though I have installed all the necessary dependencies for Google Maps. <div id="map"></div& ...

What is the best way to flatten object literal properties?

I have received an object from a legacy server that I need to restructure on the client-side using JavaScript, jQuery, or Underscore.js. Here is the original structure of the object: [ { "Id":{ "LValue":1, "Value":1 }, ...

Difficulty with conflicting styles when dynamically loading components in Nuxt3

I'm facing a challenge with my Nuxt 3 application where I need to dynamically load different Header components for Mobile and Desktop devices. I have created Header.vue and MobileHeader.vue for this purpose, and want to display them based on the dev ...

Challenges encountered while formatting Json strings for WCF service transmission

I need assistance in connecting a JavaScript application to a WCF service. The WCF Service I have includes the following method: [OperationContract] [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Wrapped, RequestFormat = WebMessageFor ...

Accessing the SQL database using Cypress

I am attempting to establish a connection with an SQL database using Cypress following the guidelines provided in the NPM guide. I have ensured that all dependencies are installed as specified, however, when I run the following query: cy.sqlServer('S ...

What are the best ways to create image animations on top of other images using CSS or JavaScript?

Imagine if the first image is in black and white, while the second one is colored. How can we make the black and white image change to color after a timeout period, with an animation similar to loading progress bars? Is this achievable using CSS or JavaScr ...

Which should take precedence in a URL: the hash or the querystring?

While some online articles suggest there is no standard for the placement of querystring and hash in a URL, we have continued to observe common practices. This leads to the question: what is the best approach for including both a querystring and hash in th ...

Problem with AWS Lambda function handler failing to insert data into Athena

Trying out a sample code snippet for Amazon Athena to test data insertion, but it's not working as expected. The CloudWatch logs don't show any output after the statement execution is completed. Even when switching to a simple select statement, t ...

The deletion of property '1' from the [object Array] is not possible

How to Retrieve a List in My Components Using Input : @Input() usersInput: Section[]; export interface Section { displayName: string; userId: number; title: number; } Here is the Value List : 0: displayName: "بدون نام" ...

Tracking the progress of file uploads using Ajax

Currently, I am working on integrating file upload using Ajax and Php on my local Apache server. This is strong text. $('.uploadButton').click(function(){ var formData = new FormData($(this).closest('.fileUploadFor ...

Is it possible to receive real-time updates for a specific location in Cesium

I am currently developing a live tracking application using Cesium, and I'm encountering an issue with updating the point location on the map in real-time. Currently, my Cesium viewer successfully receives the data from the server in JSON format and ...

Passing unknown values to external scripts in an Angular JS controller: A step-by-step guide

I am currently working on a project that involves integrating a third-party commenting service. Within the controller, I am utilizing a factory to fetch the JSON feed for the articles. The initialization function of the controller includes the 3rd party Ja ...

Clicking the button to send the form using JavaScript

Currently, I am dealing with a shopping cart plugin that relies on a basic form on the product page to send values such as price and product name. However, I am facing an issue where this plugin uses a standard submit button to transmit the values, and I w ...

Implement a functionality where data is fetched from a MYSQL database using JSON when an item is clicked on the list

As a newcomer to android development, I am facing some challenges in incorporating a basic feature into my project. The application I am working on is designed for professors to view a list of students who are under probation in the database. My goal is ...

Unable to initiate the server generated by the express.js generator

Currently, I am trying to set up an Express.js server using their generator. Following the documentation, I was able to successfully create the basic structure. However, when attempting to run the prescribed command (SET DEBUG=transcriptverificationserver: ...

Is there a way to retrieve the response body in Express framework?

In my NodeJS API using Express, I am attempting to save the response body of a request. To achieve this, I have created two middleware functions. app.use((req, res,next) => { res.status(404).json({ errors: [{ field: "url", ...

The issue I am facing involves a 404 not found axios error when attempting to send a post request

I am attempting to send data via a post request from react.js to express.js using axios, but I keep encountering a 404 not found axios error. You can view the error image here. Below is my code: export default function Upload() { const [state, setState ...