Working with AJAX requests in .NET Core

Clicking on the "Forgot Password" link should open a popup. Upon clicking the "Send email" button in the popup, a POST request should be sent and then move to the next popup for verifying the OTP.

Here is the code for the link that triggers the modal to open:

<label class="flex">Password <a href="#" class="ml-auto  small" data-toggle="modal" data-target="#modal-1">Forget Password?</a></label>

Modal popup code:

<div class="modal fade" id="modal-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
                    <h4 class="modal-title">Modal title</h4>
                </div>
                <div class="modal-body">
                    <p>Modal 1</p>
                    <input id="forgotPasswordEmail" type="text" class="form-control" placeholder="Email" required>
                    @*<a href="#modal-2" data-toggle="modal" data-dismiss="modal">Next ></a>*@
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                    <button id="sendOTP"  type="button" class="btn btn-primary" >Send email</button>
                </div>
            </div><!-- /.modal-content -->
        </div><!-- /.modal-dialog -->
    </div><!-- /.modal -->

AJAX call to asp.net core controller:

 <script type="text/javascript">
            $("#sendOTP").click(function (e) {
                alert("Hi");
                e.preventDefault();
                $.ajax({
                    type: "POST",
                    url: "/Auth/ForgetPassword/",
                    data: {
                        userName: $("#forgotPasswordEmail").val()
                    },
                    success: function (result) {
                        alert(result);
                    },
                    error: function (result) {
                        alert('error');
                    }
                });
            });
        </script>

There seems to be an issue with triggering the function, as indicated by not receiving the alert when the AJAX function is called. Any suggestions on what might be missing would be greatly appreciated.

Answer №1

Everything seems fine on my end. It's possible that the issue is due to a conflict with the element's id. Have you checked if there are any other elements using the same id sendOTP? You might want to consider using a name selector instead.

<button id="sendOTP" name="sendOTP" type="button" class="btn btn-primary">Send email</button>

<script type="text/javascript">
    $("[name=sendOTP]").click(function (e) {
        alert("Hi");
        e.preventDefault();
        $.ajax({
            type: "POST",
            url: "/Auth/ForgetPassword/",
            data: {
                userName: $("#forgotPasswordEmail").val()
            },
            success: function (result) {
                alert(result);
            },
            error: function (result) {
                alert('error');
            }
        });
    });
</script>

Update:

<button id="sendOTP" onclick="sendOTP()" type="button" class="btn btn-primary">Send email</button>

<script type="text/javascript">
    function sendOTP() {
        alert("Hi");
        $.ajax({
            type: "POST",
            url: "/Auth/ForgetPassword/",
            data: {
                userName: $("#forgotPasswordEmail").val()
            },
            success: function (result) {
                alert(result);
            },
            error: function (result) {
                alert('error');
            }
        });
    }
</script>

Answer №2

It seems that using "e.preventDefault()" might not be necessary in this case, as it is typically used when submitting a form via the onSubmit attribute. Instead, you can define your function and event listener like the example below, which should work fine.

$("#buttonId or...").click(function () {
    alert("Hi");
    $.ajax({
        type: "POST",
        url: "/Auth/ForgetPassword/",
        data: {
            userName: $("#forgotPasswordEmail").val()
        },
        success: function (result) {
            alert(result);
        },
        error: function (result) {
            alert('error');
        }
    });
});

I believe that solution will suffice.

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

Having Trouble Creating the production APK in React Native

Having trouble generating an APK after following the steps outlined in the documentation. Build Failed even though I tried: 1. cd android 2. gradlew clean "build Successful" 3. gradlew assembleRelease "BUILD FAILED" with this Erro ...

Having troubles with your jQuery script on Internet Explorer?

I am facing an issue with my script. It is located in an external file and called at the beginning of my HTML page. The script involves an Ajax request that constantly checks a database for updates. When an update is detected, it triggers a specific functi ...

Exploring Angular's Implementation of D3 Force Simulation

Looking to incorporate a d3 force simulation in my Angular app. I have a run method that initializes and sets simulation options, as well as a ticked method that updates the simulation on each tick. However, I've encountered a few problems with this s ...

"Using JavaScript to Reset a Dropdown Field: A Step-by-Step

Hello, I have attempted to use the code below in order to reset the number of adults dropdown field when clicking the reset button. However, the dropdown field is not resetting as expected. Can you please suggest a solution? Adult Dropdown Code: <sele ...

Toggle visibility of buttons according to the selection in a dropdown menu

I am currently working on an aspx page that features a dropdown list and four buttons. The selection made in the dropdown list determines which combination of buttons are displayed. My current approach involves using AutoPostBack and the selectedChanged s ...

Incorporate create-react-app with Express

Issue - I am encountering a problem where I do not receive any response from Postman when trying to access localhost:9000. Instead of getting the expected user JSON data back, I am seeing the following output: <body> <noscript>You need to ...

Issue with offset calculation in bootstrap table occurs when the bootstrap-table is closed and the window is resized

In a recent project, I utilized the bootstrap table. However, upon closing the bootstrap table with the following script: $(document).ready(function () { $(".removetable").click(function (e) { $(".table-aria").remove(); ...

Unlocking the Secrets of Json Data with Knockout: A Guide

I'm struggling to create a Typewriter Effect using knockout because I can't seem to store my data inside the table properly. Despite researching for weeks, I lack the fundamental knowledge to solve this issue on my own. This is my first time seek ...

What is the process of submitting a webhook request using a Google Docs extension?

Is it possible to develop a Google Docs add-on that can send an AJAX call to a webhook? I attempted the following code, but encountered an error. Error ReferenceError: "$" is not defined. (line 5, file "") Code function myFunction() { var arr = &ap ...

Testing components in React Native using asynchronous Jest methods

I have a component that triggers a fetch request when it mounts and then displays the results. I've been struggling to create a test snapshot of this component after the request is completed. I've searched on various forums like SO but haven&apo ...

What is causing this issue that is preventing me from async rendering Vue components?

I am new to working with Vue and I am attempting to lazy load a Component. However, I encountered an error that seems to be related to a syntax issue. Below is the code snippet: <template> <div class="container"> <h1>Asy ...

Discover how to open and read a .DXF/.DWG file using C# programming

Currently, I am trying to read a .dxf file using a c# library. Although it is able to successfully read the file, I am encountering an issue where it cannot write all layers. My goal is to extract and output a comprehensive list of all layers from the fil ...

The process of utilizing a jQuery variable retrieved from a PHP function

I've hit a roadblock and need some assistance. Let me provide you with some context. Currently, I'm working on a Wordpress website that utilizes a gallery plugin. Each gallery has a unique ID, and my goal is to switch the displayed gallery when ...

Differences in results from C# LINQ OrderBy with explicit culture across various .NET versions

I have a set of Korean and English words that need to be sorted in such a way that the Korean words appear before the English ones. My specific problem is similar to the one discussed in this Stack Overflow post: C# linq order by depending on Language De ...

What is the method for setting a default image to be preloaded in filepond?

Currently, I am working on a Laravel view for editing a record which includes an associated image. My goal is to have the image preloaded inside the input file so that when you submit the form, the same image is sent or you can choose to change it. // Con ...

Error: angular-cli encountered an unexpected token syndrome

The current node version being used is v5.7.0. I am attempting to install/update angular-cli to the latest version in order to support angular-4 I upgraded npm to the latest version using powershell as suggested by the node team. The npm version after t ...

Open a new window in Internet Explorer instead of Chrome using window.open

In the development of my MVC application, I encountered a challenge regarding opening a specific URL in Internet Explorer. While it functions correctly for IE users, those using Chrome or Mozilla are redirected to their respective default browsers when uti ...

What are the best methods for querying and updating a self-relation in Prisma?

I recently obtained some self-relation tables directly from a specific Prisma example. model User { id Int @id @default(autoincrement()) name String? followedBy Follows[] @relation("follower") following Follows[] @rel ...

Ajax calls for validations are failing to trigger a response from PHP

I am currently working on validating my signup form using PHP and AJAX, but unfortunately, I am not receiving any response value. Below is the AJAX code snippet I am using: <script type="text/JavaScript"> function frmValidation(str) { ...

Tips for reactivating all the deactivated rows using jQuery

I am new to using jQuery and I have encountered a problem with enabling all the rows that I previously disabled. I managed to disable the rows but I am unsure how to re-enable them. In my code, initially, all rows are disabled. However, when I attempt to c ...