My ASP.NET application is experiencing issues due to an input field within a <form> element

My ASP.NET web application features a straightforward login page with input fields for email address and password. Upon clicking the 'Login' button, the 'login_user()' function in the 'app.js' file is triggered.

@section Scripts {
  @Scripts.Render("~/bundles/app")
 }

 <div class="row">
     <h3>Log In</h3>
        <label>User Name</label>
        <input class="form-control" type="text" autocomplete="on" id="loginEmail" />

        <label>Password</label>
        <input class="form-control" type="password" id="loginPassword" />

       <button onclick="login_user()" class="btn btn-default">Log In</button>
 </div>

The login_user() function :

function login_user() {
    var UserName = $('#loginEmail').val();
    var PassWord= $('#loginPassword').val();

    var loginData = {
        grant_type: 'password',
        username: UserName,
        password: PassWord
    };

    var TokenEndPoint = baseUrl.concat('Token');
    $.post(TokenEndPoint , loginData,
    function (data) {
        // Cache the access token in session storage.
        sessionStorage.setItem(tokenKey, data.access_token);
        localStorage.setItem(userKey, data.userName);
        // Now we have the token we can setup the header for each subsequent call
        $.ajaxSetup({
            headers: {
                'Authorization': 'Bearer ' + data.access_token
            }
        });
    }).fail(showFailToLogin);

}

Although functional, the browser does not remember usernames and passwords, even with 'autocomplete="on"'. Research reveals that this feature only works when input fields are enclosed within a form.
However, wrapping the inputs with <form>..</form> tags causes malfunctions in my app. Clicking the 'Login' button no longer triggers the login_user() function, but submits form data to the ASP.NET server instead. This results in an endless loop of returning to the empty login page. It seems to be related to the default 'submit' action of form controls, but I'm struggling to disable it.

Answer №1

It appears that you are not customizing the default post method of the HTML form tag. Instead, it is submitting the form without redirecting to the intended method. For more information on this topic, please refer to the following link: Click here to learn about FORM METHODS

Answer №2

To ensure the buttons in the form are properly marked as "button," follow these steps:
For example:

<button type="button" onclick="login_user()" >Log In</button>

It's important to note that, based on the specification, the default type of a button is "submit"
Refer to: https://www.w3.org/wiki/HTML/Elements/button
(credit to Dean.DePue for mentioning this in the comments)

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

A dynamic website that fills the entire screen, featuring a subtle scroll effect that is activated with a

After building a fullscreen website using Bootstrap and the jumbotron feature, I added a 10px border with body padding for extra styling. Here is the HTML structure: <div class="row"> <div class="jumbotron indx-BG" > ... </div> ...

Utilizing a NodeJs Express app.get to manage both query strings and parameters

In my quest to develop a REST Service, I have crafted a route that triggers the execution of a stored procedure and retrieves JSON results. app.get('/spparam', function (req, res) { var sql = require("mssql"); // Database configuration var id=0 ...

What steps should I take to incorporate this feature into my Meteor project?

After successfully installing the type.js package, I discovered that the code works fine when directly executed in the console. Here is the code snippet: $(function(){ $(".typedelement").typed({ strings: ["You don&apo ...

Exploring the capabilities of utilizing filters within a ternary operator in AngularJS

Can a filter be applied to a variable in the template within a ternary operation? <img ng-src="{{ image_url && image_url|filter:"foo" || other_url }}"> In this scenario, the filter is custom-made and I prefer not to alter it to accommodate ...

The sequence of HTML5 DragDrop Enter and Leave events occur consecutively

I am encountering a problem with a simple drag & drop effect where the class name is changed when the drag enters or leaves, resulting in continuous entering and leaving. Take a look at this basic HTML code: <div class="box"> <div cla ...

Maintaining selectized functionality in shiny selectInput within a DT datatable even after updating the data

Within my Shiny application, I have implemented a DT datatable that includes selectInputs which are dynamically updated based on user input. To enhance the styling and search functionality of these selectInputs, I have utilized JavaScript to bind/unbind an ...

What is the best way to add additional buttons to my React App after the initial button has been clicked?

Currently, I am in the process of developing a CSV file loader that converts data into JSON format. The loader will consist of three buttons: 1. The first button allows me to select a file from my computer and load the CSV data for conversion to JSON. 2. ...

Employing PHP for the purpose of updating the content within a <div> element solely when the submit button of a <form> is clicked

I have a unique issue with my website structure. I have an 'index' page that dynamically replaces the content of 'mainContents' when any button in the navigation bar is clicked. The purpose of this design is to reload only the necessar ...

The dropdown feature is failing to display complete words in the submitted output when there is a

Attempting to craft my inaugural PHP function – a dropdown menu – has been mostly successful, however, upon submitting/posting the data, only the initial word of options containing spaces appears in the output. For instance, if I include 'First N ...

Is there a way to resolve this issue? (An error occurred: TypeError - res.json is not a valid function)

When attempting to add an object to my MongoDB database const response = await fetch("/api/contact", { method: "POST", body: JSON.stringify(data), headers: { "Content-Type": "application/json", }, }); I encounter the error message ...

Ways to target only the adjacent div

My goal is to target only the next div with the class name indented. Each indented div should have the same id as the <li> element right before it. Currently, I want each div with the class name indented to have the id of the previous <li>. He ...

Tips for properly linking external JavaScript files to HTML documents

I decided to delve into the world of HTML and stumbled upon this interesting js fiddle link http://jsfiddle.net/xfkeM/ Now, I am attempting to construct a basic webpage, but unfortunately, the desired output seems to be eluding me. Below is a snippet of ...

What causes an error to occur during the token creation process?

private static void GenerateAuthToken() { HttpClient httpClient = new HttpClient(); httpClient.DefaultRequestHeaders.Add("grant_type", "client_credentials"); var userPassJson = "{\"username\": \"mucode\", &b ...

Retrieve JSON Data Using Angular in a Wordpress Environment

I need assistance with displaying a JSON Array in <li>'s within a Wordpress Template. Here is the specific JSON file: I am completely unfamiliar with how to achieve this. This is the HTML code I have: <div ng-app="appExtern" ng- ...

Steps for verifying a user's username during the registration process with express validator

In developing a back-end API for authentication/authorization using Express and Node, I have integrated MongoDB to handle data storage. To validate input requests, I have opted to utilize the express-validator library. One particular validation requiremen ...

Tips for altering the appearance of a header when clicked on?

I am trying to change the internal style sheet in the "style" head when a user clicks, without using inline styles. I have successfully added new CSS for divone as text, but I can't seem to delete the old one (element.classList.remove("#divone");). Is ...

datetime-local format changing after selection

In an ionic application running on an android system, there is a issue with the formatting of <input type='datetime-local'> inputs. After a user selects a date, the Start input is formatted differently than the Ende input. Attempts to use t ...

Modifying the key of a JSON file

One of the challenges I'm facing involves handling a JSON file that is being inserted into MongoDB. "entities": [{ "desctype": "Location", "text": "Marília", "relevance": 0.966306, "disambiguation": { "subtype": [ "City ...

Error: IE does not recognize the 'endsWith' property or method in React Objects

I was using react-scripts version 5.0.1 in package.json and everything was working fine in IE. But after updating to 5.0.1, I started encountering an error that says: object doesn't support property or method 'endsWith' This has been giv ...

"Using Javascript to trigger a postback on the parent page from the child page

When I click a button, I am invoking a JavaScript function from the child ASPX page. function closeChildWindow() { window.opener.document.forms(0).submit(); self.close(); } This code snippet closes the child page and tri ...