How can we utilize user input to query the API effectively?

Currently, I am utilizing the API to retrieve anime information.

To fetch a specific anime, the endpoint is: https://nyaaapi.herokuapp.com/nyaa/anime?query={nameofanime}

I am seeking to input the name of the anime from the user.

Being new to APIs and JSON, my previous attempts using random endpoints were not successful. I attempted some JavaScript code but it was quite off.

const userInput = document.querySelector("#userInput").value;

fetch("https://nyaaapi.herokuapp.com/nyaa/anime?query=${userInput}")
  .then((response) => response.json())
  .then((quote) => console.log(quote));
<html>
<head>
<title>
anime
</title>
</head>
<body>

  <p>
    Anime: <input id="userInput" value="{naruto}" />
    <br />
    <button id="submit">submit</button>
  </p>
  <script src="index.js"></script>
</body>
</html>

What's currently functioning: The request is successfully being sent to the API and logged!

What's not working at the moment: While the request is being sent and logged, the relevant information is not showing (see image below).

https://i.sstatic.net/8IxkW.png

Edit: The third answer provided has been most helpful for my requirements. Now, I will work on displaying the logged info to the user.

Answer №1

If you want to see what happens when the input is submitted, try implementing this code snippet:

Make sure to include an input field in your HTML:

<input id="input" type="text" />

Then add this JavaScript function:

function getData(e) {
  const animeName = e.target.value;
  const apiUrl = `https://nyaaapi.herokuapp.com/nyaa/anime?query=${animeName}`;
  fetch(apiUrl)
    .then((response) => response.json())
    .then(console.log);
}

const userInput = document.getElementById("input");

userInput.addEventListener("change", getData);

Answer №2

If you want to retrieve the value of a DOM element, you can use the document.querySelector(); method.

const inputText = document.querySelector("#inputText").value;

After getting the user input, utilize the fetch() function to send an API request.

fetch(`https://exampleapi.com/data?search=${inputText}`).then((response) => {
       console.log(response);
})

Answer №3

I have previous experience working on a similar project which could serve as a helpful starting point for you.

window.onload=function(){

        const input = document.getElementById("input");
        const getName = document.getElementById("getName");

        getName.addEventListener("submit", e => {
            e.preventDefault();
            var inputVal = getName.value;
            var api_url = "{apiurl}" + inputVal;

            function refreshData() {
                fetch(api_url).then(response => {
                    response.json().then(json => {
                        let dataset = json;
                        let output = formatResponse(dataset);

                    })
                    .catch(error => console.log("not ok")); 
                })

            
        };
});
};
<form id="getName" class="search">
            <input type="text" id="input">
            <button id="submit" type="submit">Search</button>
</form>

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

Which is better: using Regular Expressions with preg or substr?

My task involves processing multiple values, mostly strings, and I'm looking for the best approach to use in this scenario. Within a foreach loop, I need to validate and store modified values in a database. This is an example of the structure: fore ...

What is the best way to eliminate a character from a string using a loop?

Having trouble getting my program to successfully remove a character from the user-input string due to an error occurring within the loop. (On another note, is adding a character to the string essentially the same code with minor modifications?) PS: Just ...

Having trouble displaying API JSON data in a Vue.js table component

In my HTML file, I have implemented fetching data from an API and displaying it in a table successfully. Now, I am trying to convert the HTML file to use Vue.js, but encountering some issues. Despite being able to fetch data from the API with Vue, the tab ...

Retrieve a single value from a JavaScript array

There must be something simple I am missing here, as all the search results I found relate to looping over arrays, which is not what I want. My ajax call returns a response in the form of a straightforward array. When I use console.log(response); in the s ...

When validating with Sequelize, an error occurred due to one or more columns being undefined:

Hello everyone, I'm facing some issues. Can anyone explain why this.day_number and this.teacher_id are coming up as undefined? 'use strict' module.exports = (sequelize, DataTypes) => { const Teacher = sequelize.models.teachers ...

Steps for transforming a JSON into a Class to generate objects

My JSON data is displayed below: var nodeclienthash={ socket:null, init : function() { // Initializing socket.io this.socket = new io.Socket(this.config.host, {port: this.config.port, rememberTransport: false}); } }; I am currently looking t ...

JavaScript: create a new array by selecting elements from an existing array (similar to C#'s Select

If I have an array of 3 integers in C#, [1,2,3], I can transform that array into another with the .Select method like so: [1,2,3].Select(e => new { Id = e, Name = $"name:{e}"), resulting in a new array with 3 objects. Is there a way to achieve the same ...

Retrieve the value of a variable from a JSON decoded response

My json response has been decoded into an array $data: stdClass Object ( [outboundSMSMessageRequest] => stdClass Object ( [deliveryInfoList] => stdClass Object ( [deliveryInfo] => stdClass Object ( [address] => 8606142527 [deliveryStatus] => ...

Struggling to apply the onclick function to an HTML element

I am working with an array of 10 elements that I need to shuffle and display, which my current code is able to do. However, the issue arises when I try to add functionality to show an alert message if any of the displayed array elements are clicked. The ...

Resizable dynamic table in HTML

I am currently developing a flex table in HTML, constructed of multiple div elements. My goal is to make it resizable without using the traditional table tag. The layout of my table is similar to the one showcased in the following link. How can I achieve t ...

Having trouble with Resizing Images in jQuery despite successful image rotation

I am facing an issue with rotating and resizing an image using an HTML5 form. The rotation angle can be adjusted in steps of 90 degrees, but the image should always remain 770px wide regardless of its orientation (landscape or portrait). Despite creating ...

Merging arrays with the power of ES6 spread operator in Typescript

My goal is to merge two arrays into one using the spread object method as shown in the code snippet below: const queryVariable = { ...this.state, filters: [...Object.keys(extraFilters || {}), ...this.state.filters], } The this.state.filte ...

How to read post data in JSON format using body-parser in a Node.js Express

I have included the dependencies "body-parser": "1.15.0" and "express": "4.13.4" I am attempting to extract the json data from the body section of an incoming http post request. This is the code I am using: var express = require('express'); var ...

"Exploring the Seamless JSON Deserialization Feature of Jersey MOXy with Case-Insensitive Handling

Seeking assistance in setting up a Jersey 2.x REST-service that consumes JSON-Response via POST using MOXy. Currently, the setup works smoothly only if all JSON-attributes match the properties in my POJO exactly. Is there a way to configure MOXy to allow ...

Issues encountered while optimizing JSON file in a ReactJS program

I'm struggling with utilizing Array.prototype.map() in Javascript Specifically, I'm reformatting a JSON file within my react app, which looks like: { "id": 1, "title": "Manage data in Docker", "description": "How to use v ...

Showing information in a textarea using ejs

I am currently attempting to extract data from a mongo database and display it in a textarea. The purpose of this is to allow me to modify the database information without directly interacting with the database itself. While I can successfully display the ...

Mastering basic operations with Vue in Laravel

Recently, I delved into learning vue.js after having experience with angular 2+. The transition seemed smooth after watching tutorials. However, when I tried to create a simple app where a user can post a story with comments, I found myself struggling wit ...

What is the best way to set up <Input> to restrict input to only include letters, spaces, and the backspace key

I have created a 15 by 15 matrix displayed as an HTML table where each cell contains an input box. I am looking to restrict user interaction so that they can only: Input English letters Delete characters using backspace Use the spacebar In the future, nav ...

json data hidden from sight in jQuery

Snippet of HTML Code: <select name="ser" id="ser" class="form-control" onchange="getPrice(this.value);"> <option value="">--Select--</option> <option value="Value11">Value1</option> <option value="Value2">Value2</op ...

Issues arise when attempting to generate multiple instances of textboxes and textbox groups dynamically within AngularJS

Here is the code snippet: <body> <div ng-app=''> <div ng-controller="questionCtrl"> <div> <ul /> <li ng-repeat="prdElement in palletElement"> <input type= ...