After entering the author's name in the text box, I am attempting to showcase a quote, but inexplicably, nothing is appearing. What steps should I take to resolve this issue

Every time I enter the author's name in the text box and hit the button to show the quote, it shows undefined. It appears that my button and textbox are not properly connected. How can I resolve this issue?

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Quotes</title>
</head>
<body>

<label for="getQuotes"gt;Find Quotes (Enter Author Name)</label><br>
<input type = "text" id="getQuotes" name="getQuotes" placeholder="Search" style="margin:10px" size="50"/><br />
<button id="FetchQuotes" onclick="getQuote()"  style="margin:10px">Fetch Quotes</button>

<p id="qotuotes"></p>

<p id="author"></p>

<script>
    async function getQuote() {
        //const author = Boolean(false);
        let url = 'https://jaw1042-motivate.azurewebsites.net/quote';
        let author = document.getElementById('getQuotes').value;
        if(author) {
            url = 'https://jaw1042-motivate.azurewebsites.net/quote?author= ';
            console.log(url + author);
        } else {
            console.log(url);
        }
        fetch(url)
            .then(async (response) => {
                if (response.ok) {
                    console.log("Response code: " + response.status);
                } else if (response.status === 400) {
                    console.log("Unable to find any quotes by specified author: " + response.status);
                } else {
                    console.log("No quotes have been loaded: " + response.status);
                }
                const val = await response.json();
                console.log(val);
            }).then(data => {
            document.getElementById('quotes').innerHTML = data;
            document.getElementById('author').innerHTML = data;
            console.log(data);
            alert(data);
        });
    }
</script>
</body>
</html>

Answer №1

Make sure your then functions are correct when handling the direct result of the fetchAPI. You need to run .json() or .text() on the data received in order to use it properly. Avoid assigning anything new to the variable storing the fetched data as it may lead to issues.

Check out the updated JavaScript code below:

function getQuote() {
   fetch("https://krv1022-motivate.azurewebsites.net/quote")         
     .then(res => res.text())
     .then(data => {
         document.querySelector(".quote").value = data;
     });
}

If you're facing CORS issues with the provided URL, consider checking the correctness of the URL or resolving any CORS-related problems.

Furthermore, ensure that the Author's name received from the end user is being sent to the backend as well. If you intend to send this data using a GET method and the backend expects the author's name to be named getQuotes, make adjustments accordingly for completeness.

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

Create an HMAC signature for the Google Maps at work API using Apigee Edge

Currently attempting to create a valid signature for the Google Maps API within Apigee edge. Although I have tried using a JavaScript callout, I have been unsuccessful. While I am able to generate signatures, they are not what Google is looking for. My su ...

Using a Second List Element in CSS Image Rollover Map with jQuery

I have been utilizing this interactive map from Wolf's website, but I am interested in incorporating a secondary list of countries alongside the existing one as the base for the script. However, due to presentation reasons, the second menu cannot resi ...

Issue with readonly property not functioning properly in jQuery

In my code, I am multiplying the input values of the first two columns (answer1 and answer2) and storing the result in the third column (answer3). I have set the third column input to be read-only using jQuery. However, when I click on the third column in ...

What could be causing the columns in this table row to not display any borders?

On my HTML page, I have included an image which showcases a table. However, there seems to be an issue with the borders of the table - the vertical lines are not appearing as expected and instead showing around each button. Additionally, the horizontal lin ...

The functionality of react-waypoint's onEnter/onLeave event handlers seems to be malfunctioning

Recently, I experimented with react-waypoint to control the visibility of a div. The code works as intended by hiding the div when it reaches the waypoint inside onEnter. When the div is inside, the isInView state becomes true, which in turn triggers the d ...

What is the best way to use hasClass in a conditional statement to display text based on the content of a different div element?

Let's say we have the following HTML code: <div>New York</div> Now, we want to add another div like this: <div>Free Delivery</div> How can we achieve this using JavaScript? ...

Managing modules within the node_modules folder that have dependencies on .css files

Currently, I am involved in a project where we are utilizing a custom UI library that includes some dependencies. These components come with their own corresponding .css files. The structure of the source code looks like this: |- src |-| |- components ...

The event binding for input with the specific class `.SomeClass` in the document is functional in Chrome, but encounters issues in Internet Explorer

I am facing an issue where I have a span with the contenteditable attribute and a function to detect input within it. //TextArea <span class="SomeClass" contenteditable></span> //Function $(document).on("input", ".SomeClass", function () { ...

When the page is scrolled, trigger a click event on the next button in

Currently, I have a listing page that features pagination at the bottom. However, my goal is to transform this into an infinite loading page. The issue I am facing is that when the click event triggers after scrolling to the bottom, it makes calls for pag ...

When entering "schemaname.tablename" into the id field using a Django Jinja template, the Bootstrap modal pop up malfunctions

Here is the HTML script that I am using to send a schema_name.table_name to the 'id' attribute of my modal. However, the popup modal does not display and breaks. You can see the code below: Please note: when I only send the table_name to the &ap ...

Is there a bug with text rotation in CSS 3?

I'm having trouble understanding how text rotation works in CSS3. For example, when I try to rotate text like you can see here, the rotated text never seems to be in the correct location, despite setting properties like: right: 0; bottom: 0; There ...

Having difficulty running assessments on the connected components

I have encountered an issue while using the MERN stack and Redux. Specifically, I am facing errors when trying to write test cases for certain components. The error message I receive states: "Could not find "store" in the context of "C ...

Adding input values to a jQuery Ajax POST request

I am currently attempting to send form values to a remote API using AJAX. The necessary information I require from the HTML form element includes the author, string, false, and true. At the moment, I have hard-coded some values but... function sendData ...

Creating a fresh array in JavaScript

Attempting to create a new array with specified values. Scenario 1: var x = new Array(3).map(()=>1); At this point, x equals [undefined * 3] Scenario 2: var x = [...new Array(3)].map(()=>1); Now x is [1,1,1] Can anyone provide assistance on wh ...

Transmit information from JavaScript to the code behind upon initial page loading

I'm currently working on a web application and I need to retrieve data about the local environment of the machine that is accessing the application. To achieve this, I am using a small JavaScript script like the one below: <script language="javasc ...

Bring in the node_modules from an absolute path instead of a relative one

I am facing an issue while trying to import a custom framework that I published on npmjs.org. I have created a .js file and a .d.ts file for this framework. Initially, there are no errors during the import process until I compile the code. All the map lin ...

There is a single div sandwiched between two others, with each of the surrounding divs reaching the edge of the browser

Require a small space between the middle div and the two on each side. The middle bar should have a fixed width. Here is my attempt so far, but it seems messy: <!DOCTYPE html> <html> <head> <style> #container { width: auto; ...

Is there a way for me to generate a tab that shows content when hovered over?

Is it possible to create a tab that displays a vertical list of redirections when the mouse hovers over it, and hides when the mouse is moved away? This seems like a challenging task. Can someone guide me on how to achieve this, especially if it involves ...

Refresh a webpage content dynamically without the need to reload the entire page

How can I implement YouTube's page navigation system that does not require the entire page to reload when switching pages? Do I need to incorporate Javascript or utilize an API for this functionality? ...

A div element set to a width of 100% that holds a lengthy text will expand to the entire width of the window,

Check out this simple webpage: https://jsfiddle.net/enxgz2Lm/1/ The webpage is structured with a side menu and a tasks container. Within the tasks container, there is a row container that includes a checkbox, title on the left, and details on the right. ...