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

What is the process for extracting an array from an object?

How can I retrieve an object from an array using Node.js? I have tried the code below, but it's returning the entire object. What I actually need is to only print the name, for example, just "sethu". Code: var sethu = [{ name:'sethu', ...

Turn off link preview feature on Android messages

As a developer, I am looking for a way to disable or hide link previews on Android devices when someone receives a text message with a link to our website. I still want the URL address to be visible, but I prefer to keep the link previews on IOS devices. I ...

Stop form from submitting on bootstrap input, still check for valid input

Encountering a dilemma here: Employing bootstrap form for user input and utilizing jQuery's preventDefault() to halt the form submission process (relying on AJAX instead). Yet, this approach hinders the input validation functionality provided by boots ...

Is it possible to import Vue directly from the "/path/to/vue.js" file without using npm or NodeJs?

Is it possible to build a web app using just a single index.js file and importing other available files like shown in this image: https://i.stack.imgur.com/02aFF.png encountering the error message: import not found: default Do you have to use Vuejs wit ...

Rendering an object as a React child is not allowed (object found with keys {this}). To display multiple children, make sure to use an array instead of an object

Encountering an error: How can I resolve this issue in React? The file relates to the layout I am utilizing Visual Studio export default class Layout extends React.Component { constructor(props) { super(props); this.identify = this.identify.bi ...

Tips for effectively implementing correct reselection in a React-Redux application

I have a system that allows users to search for data based on their input. I am currently implementing reselect in my application. import React, { useEffect } from "react"; import { useDispatch, useSelector } from "react-redux" ...

Converting a Class Component to a Functional Component in React: A Step-by-Step

I need to refactor this class-based component into a functional component class Main extends Components{ constructor(){ super() this.state = { posts:[ { id:"0", description:"abc", imageLink: ...

Is there a way to transmit the ENTER key press to the page setup dialog within Internet Explorer 7?

My code is designed to change the page orientation. It functions correctly in IE6, but encounters issues in IE7. Specifically, it stops at %a and fails to input the enter or tab keys needed to press 'OK'. var shell; function SetPrintProperties() ...

What methods can be utilized to enhance the visual appeal of a threejs model

I'm currently working on enhancing the visual quality of my 3D models, aiming for smoother edges and more realistic shadows. To achieve this, I am experimenting with an OBJ file format. Here's the code snippet I'm using to load and display t ...

What is the best way to target the iframe within the wysihtml5 editor?

Currently, I am utilizing the wysiwyg editor called wysihtml5 along with the bootstrap-wysihtml5 extension. As part of my project, I am designing a character counter functionality that will showcase a red border around the editor area once a specific maxl ...

Experiencing a 404 error after attempting to access an endpoint following a successful MSAL Azure AD

Incorporating the UserAgentApplication.loginPopup function to authenticate users on our Azure AD has been a challenge as we transition from an ASP.NET MVC application to a Vue.js front end and ASP.NET 'API' backend. The goal is to pass the access ...

Submitting a form with Multer when the user chooses to upload a file or not

I have integrated multer into my express app for handling form submissions. The issue I am facing is with the optional image upload feature in the form. Users have the choice to add a photo if they want, but they should also be able to submit the form wi ...

NiFi utilizes string manipulation functions such as padRight within JoltTransformJSON

Is it possible to utilize string manipulation functions like the example below in JoltTransformJSON? ${BIG:padRight(5, '@')} Reference: Expected Result: BIG@@ Similar to: "small_toUpper": "=toUpper(@(1, small))", "BI ...

Add the URL link according to the specific domain name

I am looking for a way to attach additional URL parameters to any links that contain example.com on a webpage. The current script I have only works if the link does not already have parameters attached to it. <script> document.body.innerHTML = d ...

Improper ordering using insert method within a forEach loop

I have an array containing objects that I need to import into a sqlite3 database using a forEach loop. The process is working correctly, but I noticed that the objects are not being imported in the same order as they appear in the database. This is my app ...

Incorporating Ruby on Rails: Sending a fresh POST request to API and instantly

I'm a beginner in the field of ruby on rails. Our website allows users to search and receive a list of results. Now, I want to incorporate sorting functionality for the results (by price, rating, etc). The API handles the sorting process, so all I ne ...

Encountering the "test exited without ending" error while using asynchronous forEach loops with tape

My Current Project Edit: I created a repository with a simplified version of the issue I am facing. Currently, my focus is on setting up automated frontend testing using tools like browserstack, selenium-webdriver, and tape. More information about tape ...

What is the schedule for updating files?

My code runs in an infinite loop and can be stopped by pressing control C in the terminal. It includes the function json.dumps(dictionary, outfile). I've observed that data is not written to the file until I manually terminate the program with contro ...

Retrieve numerous tables as individual entities in a single query

In the process of creating an interface where the selection in the first dropdown influences the available options in six subsequent dropdowns. For each dropdown, the values and display names are retrieved from a table as shown below: $arr = arra ...

An error was thrown at line 474 in module.js

After recently installing nodejs on my laptop, I'm struggling to run a js file in the node environment. I attempted using this command: node C:\Program Files\nodejs\file.js, but encountered the following error: module.js:474 thr ...