Looking for a solution to the issue below? A pesky JavaScript/Ajax dilemma is causing trouble

Hey there! I'm currently working on an ASP.NET Core application that utilizes AJAX and a login.js file to send data to my API. However, when trying to execute JSON.stringify(formData) in the browser, I encounter the error message: Uncaught ReferenceError: formData is not defined at :1:16. I've tried several solutions to tackle this issue, but it seems persistent. Any suggestions?

function logar(event) {
    event.preventDefault();

    var formData = {
        email: $("input[name='email']").val(),
        password: $("input[name='password']").val()
    };

    $.ajax({
        type: "POST",
        dataType: "json",
        contentType: "application/json; charset=UTF-8",
        data: JSON.stringify(formData),
        url: "https://localhost:7291/api/User",
        success: function (result) {
            // Success logic
        },
        error: function (error) {
            // Error logic
        }
    });
};

This is the content of my page:

@model SquadManager.Models.UserViewModel
@{
    Layout = null;
}
<link href="~/css/login.css" rel="stylesheet" />

<section>
    <h1>Authentication</h1>
<form>
        <input type="email" id="email" name="email" value="@Model.Email" placeholder="Username/e-mail" />
        <input type="password" id="password" name="password" value="@Model.Password" placeholder="Password" />
        <a href="#">Forgot your password?</a>

        <button type="submit" onclick="logar(event);">Login</button>
</form>

    <label>Don't have an account?  <a href="#">Create your account here!</a> </label>
</section>

<script src="~/lib/jquery/dist/jquery.js"></script>
<script src="~/js/login.js"></script>

Check out the console error screenshot for more details on the result: Console Error

Answer №1

After realizing that I couldn't call JSON.stringify(formData) outside of the logar function, I decided to make some changes. I modified the logar function with the following code, which now works within the onSubmit event of the form.

$('form').on('submit', function (event) {
    event.preventDefault();

    var formData = {
        email: $("input[name='email']").val(),
        password: $("input[name='password']").val()
    }

    $.ajax({
        type: "POST",
        dataType: "json",
        contentType: "application/json; charset=UTF-8",
        data: JSON.stringify(formData),
        url: "https://localhost:7291/api/User",
        success: function (result) {
            if (result.response == "ok")
                alert("Logged in successfully")
            else
                alert("Invalid credentials")
        },
        error: function (error) {
            console.log(error);
        }
    })
});

See the result 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

Every time I attempt to navigate to the login page, I find myself stuck in an endless loop

This code snippet demonstrates the router.beforeEach function in action. It checks if the client is authenticated, and if not, it redirects them to the login page. router.beforeEach(async (to, from, next) => { if ( to.name !== 'signup' || to ...

Python script for downloading audio files loaded with JavaScript

I am currently working on a Python script to automate the process of downloading English audio files from a specific website. When I click on the play button, the audio file starts to load and play, but I am unsure how to capture and download the file in ...

Tips for resizing mesh along the global axis

Have you ever used an online 3D editor that allows you to manipulate individual meshes by moving, scaling, and rotating them? This editor utilizes custom transform controls inspired by the TransformControls code from three.js. Here is a snippet of code fro ...

What Array functions in JavaScript cause changes to the original array?

Currently, I am working on developing a custom Array class in JavaScript and I'm curious about the functions that need to be overloaded in order to track any modifications made to the array. So far, I am aware that Array.push() and Array.splice() are ...

I attempted various methods but was unable to successfully call the webmethod in the code behind using jQuery Ajax and Knockout

I have attempted various solutions, such as enabling friendly URL resolution and utilizing web method with session enabled, but unfortunately, the issue remains unresolved. I kindly request your assistance in resolving this matter. Here is my HTML code for ...

How can you handle setting an array in JavaScript if a key/value pair does not exist when attempting to get it from a JSON object?

When dealing with a large JSON table stored in localStorage and a user-provided key, I need to access the associated value. However, if the key and/or value does not exist, my intention is to create them. But there's a roadblock... The JSON data prov ...

Utilize WordPress, Ajax, and Curl to seamlessly embed a PDF stream from an API

I originally had the HTML embed tag with a direct call to an API that returned a PDF stream, which worked perfectly. However, due to security reasons, I can no longer make direct calls to the API. I have transitioned to using Ajax (via WordPress) to update ...

Angular.js hierarchical model issue: grandchildren functionality not functioning as expected

Currently, I am delving into the world of Angular and exploring its functionalities. My main goal is to construct a hierarchical data structure that can be easily manipulated using a hierarchical view: Root: - addChild - child 1: { remove, addChild, c ...

In what way can a property in JavaScript alter an object?

I am a newcomer to node.js, although I have been writing Javascript for many years. Recently, I encountered an interesting pattern that has left me puzzled: a Flag that is used to set a modifier on the object. For example, in the socket.io documentation: ...

Is there a method to pre-load a CSS background image so that it can still be displayed even without an internet connection?

Situation: Imagine having a web app that shows an error message when trying to perform an action but fails due to a connectivity problem. The error dialogue has a CSS class with a background image that can't load because of the connection issue, res ...

Refresh information in form after submitting with Remix

Currently, I am utilizing the Remix Form element to display my form with various input fields. When there is a server-side validation error, the entered text in the fields remains, as expected. However, upon successful submission of the form, I would like ...

How to associate an object with a component in Angular2/TypeScript using HTTP

I am currently working on displaying a list of item names retrieved from a REST API. By utilizing the map function on the response observable and subscribing to it, I was able to obtain the parsed items object. Now, my challenge is how to bind this object ...

Utilizing the jQuery Form Plugin for efficient form handling, incorporating Ajax File Upload for

Currently, I am utilizing the jQuery Form Plugin in a project involving a complex form with file fields. The backend framework being used is Ruby on Rails. Struggling with configuring Rails to recognize the POST request type as 'text/javascript,&apos ...

Why do my session details in the stripe webhook show as undefined?

During the development of my stripe checkout session, I encountered an issue where I can successfully send information to my webhook and print out all the session details, but I am unable to access individual pieces of information. Whenever I try to access ...

What is the solution for handling undefined errors that occur when employing d3.select(this) within a Vue methods hook?

Currently, I am in the process of transferring d3 graphs from another project to my personal Vue-based project. Most aspects are functioning as expected, except for aligning labels in the arcs of a pie chart using the arc.centroid(d) method. Two errors kee ...

The URL for the Javascript chunk includes colons at https://example.com/js/chunk-vendors.b3792e11.js:18:16400

I recently completed a Vue application and used npm run build to generate the files. Upon uploading the dist folder to my Apache server, I encountered an issue where Apache was unable to locate the file when trying to access a specific part of the app (:18 ...

Utilizing Firebase 9.0.1 Functions in Vue.js 3

As a newcomer to Vue, I decided to tackle my second tutorial which involved integrating Firebase backend with Vue. However, the tutorial was based on Vue 2 and an older version of Firebase. Determined to stay current, I set out to replicate the project usi ...

What could be the reason for the onmessage listener not handling the initial SSE event?

When a client connects to a Node Express server, it creates a new EventSource. The server sends an SSE event upon initial connection and then at a 30-second interval thereafter. Strangely, the client's onmessage handler does not respond to the initial ...

Retrieve the data attribute associated with the chosen dropdown selections

I'm currently facing an issue with assigning a custom data attribute to a select box option and then transferring that value to a hidden form field. Here is the HTML I am working with: <select id="sampleorder" multiple="multiple"> <option ...

Using AJAX to make PHP function calls results in the page being refreshed each time

Currently, I am in the process of constructing a new script that requires incorporating a PHP function to send an email. My approach involves nesting a couple of Ajax calls within a JavaScript function. However, every time this function is called, it simpl ...