Issue: Although the Javascript button in the Asp.net Project appears to be clickable, it is not executing the

My friends and I have been working on a project that involves integrating an API, but we've hit a roadblock. The "ok" button, which is supposed to execute a function after uploading a photo and clicking ok, is not working as expected. Strangely, the "choose files" button works fine.

I tested the API sample in a separate solution and it worked perfectly. This makes me think there might be a mistake in the code elsewhere or some kind of blockage preventing communication with the API's web address. Unfortunately, within our project (ASP.NET razor page), the functionality doesn't seem to work.

I've tried various solutions like creating a new button, moving the JavaScript tag around, but nothing seems to fix the issue. I have omitted the API key for privacy reasons. Any assistance would be greatly appreciated!

@{
    ViewData["Title"] = "Identify a Plant";    
}
   
<!DOCTYPE HTML>
<html>

<head>
    <meta charset="UTF-8">
</head>

<body>
    <form>
        <input type="file" multiple />
        <!--<button type="button">OK</button>-->
        <button type="button">OK</button>
    </form>

    <script type="text/javascript">
        document.querySelector('button').onclick = function sendIdentification() {
            const files = [...document.querySelector('input[type=file]').files];
            const promises = files.map((file) => {
                return new Promise((resolve, reject) => {
                    const reader = new FileReader();
                    reader.onload = (event) => {
                        const res = event.target.result;
                        console.log(res);
                        resolve(res);
                    }
                    reader.readAsDataURL(file)
                })
            })

            Promise.all(promises).then((base64files) => {
                console.log(base64files)

                const data = {
                    api_key: "Die8ewFGvpw5JrRTuOEjgGR10uL--",
                    images: base64files,
                    modifiers: ["crops_fast", "similar_images"],
                    plant_language: "en",
                    plant_details: ["common_names",
                        "url",
                        "name_authority",
                        "wiki_description",
                        "taxonomy",
                        "synonyms"]
                };

                fetch('https://api.plant.id/v2/identify', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(data),
                })
                    .then(response => response.json())
                    .then(data => {
                        console.log('Success:', data);
                    })
                    .catch((error) => {
                        console.error('Error:', error);
                    });
            })

        };
    </script>
</body>

</html>

Answer №1

In my opinion, it would be more efficient to assign an "ID" to the button instead of not doing so.

I have never been a fan of the concept of simply "selecting" a button and then hoping to attach a click event to it. I believe that explicitly creating and defining a button, specifying its click event, makes the code much easier to understand and follow.

Therefore, I suggest structuring your button in the following manner:

<form id="form1" runat="server">
    <div>
        <br />
         <input id="myfiles" type="file" multiple="multiple" />

    <button id="MyButton" type="button"  onclick="sendIdentification()"   >OK</button>
    </div>
  </form>

<script type="text/javascript">

 function sendIdentification() {
    alert('start');

        const files = [...document.querySelector('input[type=file]').files];

etc.

The issue with relying on selectors for click events is that they may not always target the intended control due to elements' positions on the page. By directly including a designated button with its defined functionality, you can prevent such discrepancies.

In conclusion, setting up a specific button with a corresponding action upon clicking will streamline the process and avoid any confusion.

Answer №2

Utilizing the querySelector method allows you to attach an onClick event to the first button found within the document. Considering that the _Layout.cshtml is loaded initially, it suggests there might be a button present in that view. Have you considered assigning an id to the button and implementing the onClick event in the following manner:

document.getElementById("myButton").onclick = function sendIdentification() {
    // your code here
};

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

How to Intercept Events in Vue.js Using Plain JavaScript

I have a vanilla JavaScript file that sets up some Bootstrap/jQuery libraries. function reinitialize() { jQuery('.js-datepicker').add('.input-daterange').datepicker({ weekStart: 1, autoclose: true, todayHigh ...

Is it not possible to generate HTML tags using jQuery and JavaScript in JSF?

I'm currently working with jsf 2.0 and richfaces 4.0 to develop my application. Occasionally, I incorporate jQuery and JavaScript functions for displaying and hiding elements. However, I've encountered an issue when trying to generate tags within ...

How come when utilizing jQuery to call a PHP function, the output received is the actual PHP code?

I'm currently working with a php file that has the following code: if(isset($_GET['fn'])) { if($_GET['fn']=='generarxml') generarxml(); else exit; } function generarxml() { ...

Encountered a Server Error: Invalid hook call. Hooks are restricted to being called within the body of a function component specifically in _app.js

As someone new to React and Next JS, I am facing an issue with setting initial auth user data on the initial load from the __app.js file. Whenever I try to use dispatch, it throws an error saying "Invalid hook call". I understand that calling hooks in the ...

Trigger and Throw an Error within a Commit

Perhaps there's a more efficient approach to achieving my goal. I aim to have SQL Server trigger two types of errors - a WARNING and an ERROR - when updating a table. If a WARNING is returned, the trigger should COMMIT but display the warning to the u ...

What is the best way for a class to access parameters and methods that are defined in two interfaces that it implements?

I am facing an issue in my factory where I am generating objects based on one interface, but they implement multiple interfaces. For instance: myClass1 : Interface1, Interface2 { string blah; int num; } myClass2 : Interface1, Interface2 { strin ...

Ways to transmit data from autocorrect to a higher-level class

Previously, I raised a question about passing state for React via props on Stack Overflow: Laggy TextField Updates in React. I have now revamped my code using ChrisG's approach, where I store states in the parent component FormSection and pass them a ...

Redis VS RabbitMQ: A Comparison of Publish/Subscribe Reliable Messaging

Context I am working on a publish/subscribe application where messages are sent from a publisher to a consumer. The publisher and consumer are located on separate machines, and there may be occasional breaks in the connection between them. Goal The obj ...

The issue of Bootstrap's closed.bs.alert event not triggering when a dynamically created alert is being closed

On my page, users can search for information, triggering an alert at the top to inform them that the search is in progress. Once the results are displayed, if a user clicks the dismiss button on the alert, the main page should reload. The issue I'm f ...

The consistent failure of the 201 status node express API is causing major

I am currently working on creating an API using Express. However, when I receive a response from the server, it shows '201 created'. The issue arises when I attempt to make an HTTP request through promises and encounter a false interpretation of ...

Generate a graph by utilizing $getJSON and ChartJS

I am currently working on creating a bar chart using ChartJS and a JSON file. The data format is provided below, with each object containing information about the station name and arrival time. My goal is to populate an array where the x-axis represents St ...

Guide to retriecing a state in Next.js 14

Check out my code below: "useState" // firebase.js import firebase from "firebase/app"; import "firebase/auth"; // Import the authentication module export default async function handler(req, res) { if (req.method !== " ...

Dealing with a 409 conflict situation involving a document in Node.js using Nano library

After conducting research, it has come to my attention that there are numerous document conflicts with couchdb. While exploring a potential solution in Updating a CouchDB document in nano, I discovered the following steps: Retrieve the document Store th ...

Using target="_blank" does not seem to open a popup window in React

The issue is that the target="_blank" attribute is not working properly for the modal popup window. Instead, the link is opening in the same page and the popup is closing. <TermLink to="/legal/privacy-policy" target="_blank"> Privacy Pol ...

In React-router, I aim to transmit the location of a Link to a Route

When setting the Link in a child component like this: <Link className="article-link" to={`/newsarticle/${title}`}> I expect the Route to reflect that in the App.js component: <Route path=`/newsarticle/${title}` component={NewsPage}/> The pu ...

Is it possible to update the value of an element using JavaScript?

My goal is to manipulate the content of a specific element on a third-party web page using a JavaScript Add-on in order to display a clickable hyperlink. I have already identified the link that I want to interact with on the page, and I believe document.g ...

Encountering a connection error when trying to access a Google spreadsheet within a Next.js application

I am currently exploring Next.js and attempting to utilize Google Sheets as a database for my project. Although my application is functioning correctly, there is still an error message displaying that says "not forgot to setup environment variable". I have ...

Python error: KeyError occurs even though both the key and value are present

Currently, I am retrieving data from the opendota API. Earlier, I extracted a .csv file containing around 160 match_ids that I need more information about and then add certain values to a list. However, when I use the code snippet below to loop through th ...

What is the reason for encountering an error when using the ForwardRef with a pair tag

I am facing an issue with my React app that has 3 tsx (jsx) files: First, in my index.tsx file: import ReactDOM from 'react-dom'; import Page from './Page'; ReactDOM.render( <Page /> ...

Utilizing Angular to parse a JSON string generated with json.dumps

I am having trouble finding a solution that works for me. Currently, I am using python 3.6 (Django Rest Framework) on the server side and Angular 5 on the client side. This is the code on the server: class TypesView(APIView): def get(self,request): ...