Form validation using jQuery and AJAX

I've implemented validation in my ResetPassword function and it seems to be working fine. However, I'm facing an issue where the ResetPassword function stops working once the validation is added. Can someone guide me on how to resolve this issue? Thank you.

Here is the HTML code:

<div class="PopUpBG">
  <div class="PopUp">
    <h3 class="modal-title">
      <span>Reset Password</span>
    </h3>
    <form id="form">

      <input type="email" name="ResetEmail" id="ResetEmail" placeholder="Email Address" required/>

      <input type="submit" class="btn btn-success" value="Send" onclick="ResetPassword(this)"/>

    </form>
  </div>

</div>

Below is the code for the ResetPassword function and validation:

function ResetPassword(e) {

  var email = $("#ResetEmail").val();

  if ($("#form").validate()) {
    return true;
  } else {
    return false;
  }

  $(".PopUp").html("We have sent an email to you");

  $.ajax(
    {
      type: "POST",
      url: "/Account/loginRequestResetPassword",
      dataType: "json",
      data: {
        Email: email,
      },
      complete: function () {
        console.log("send");
        $(".PopUpBG").fadeOut();
      }
    })
}

Answer №1

The reason for the issue is that the function exits before sending the AJAX request every time, as you have used the return statement in both conditions of the if statement.

To resolve this, modify your logic to only exit the function if the validation fails:

function ResetPassword(e) {
  if (!$("#form").validate())
    return false;

  $.ajax({
    type: "POST",
    url: "/Account/loginRequestResetPassword",
    dataType: "json",
    data: {
      Email: $("#ResetEmail").val().trim(),
    },
    success: function() {
      console.log("send");
      $(".PopUp").html("We have sent mail to you");
      setTimeout(function() {
        $(".PopUpBG").fadeOut();
      }, 10000); // fadeout the message after a few seconds
    },
    error: function() {
      console.log('something went wrong - debug it!');
    }
  })
}

Furthermore, I've made changes to ensure that the successful email message will only appear after the request has been completed. The current code may display the 'email sent' message prematurely, even if there is still a chance for the function to fail.

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

c# simulating button click through injected JavaScript

Greetings, I'm seeking assistance in replicating a specific button click on a website. Here is the code for the button: <button type="button" class="btn btn-link btn-xs" onclick="getComponents('188855', '5a0f44a9d70380.12406536&apo ...

What are the possible complications that could arise from implementing this system for designing web pages?

Feeling frustrated with the limitations and compatibility issues of CSS, I decided to create a new approach for structuring webpages. Instead of relying on CSS, I developed a javascript library that reads layout instructions from XML files and uses absolut ...

I have successfully converted an SQL Join query into JSON, but now I am unsure of how to interact with the

I recently ran an SQL Join on two tables and obtained the following results: _____People_____ name: "Jane" age: 35 job_id: 1 _____Professions_____ job_id: 1 title: "Teacher" "SELECT * FROM People INNER JOIN Professions ON People.job_id = Professions.job ...

Is there a way to implement a directive wrapper for ng-grid that allows the grid options to be specified using a directive attribute?

My goal is to create a reusable directive wrapper for ng-grid, where I can dynamically apply the ng-grid options through the use of an attribute. Below is the basic structure of the code that almost achieves what I am looking for: angular.module('my ...

What reasons could lead to useSWR returning undefined even when fallbackData is provided?

In my Next.js application, I'm utilizing useSWR to fetch data on the client-side from an external API based on a specified language query parameter. To ensure the page loads initially, I retrieve data in a default language in getStaticProps and set it ...

Align component within material-ui grid

Looking to center align the same cards but not just the grid component, I need the content itself to be equally distant from the borders and each other. I've searched and tried different solutions without luck. https://i.stack.imgur.com/aZj7H.png htt ...

Integrate ThreeJs models into an Angular JS application

I have a question that pertains to my webapp development. I am currently utilizing Angular Js (v1.5/1.6) and I would like to incorporate some minimalistic 3D animated models by integrating Three Js. Although I have attempted to configure certain aspects, ...

Attempting to remove options in a Multiple Choice scenario by selecting the X icon beside each one

I'm working on a multiple choice quiz and I'd like to add a button or icon resembling X in front of each option (even in front of the radio button), so that when I click on it, only that specific option is deleted. How can I achieve this? For in ...

fetching information from a distant PHP file

I am currently using php and ajax to submit a form without refreshing the page. Below are my files - coupon.js jQuery(document).ready(function(){ jQuery(".appnitro").submit( function(e) { $.ajax({ url : "sms.php", type ...

Encountering difficulties setting cookies within the app router in Next.js

I've been diving into next.js and I'm trying to figure out how to set a cookie using the code below. However, I'm encountering an error: "Unhandled Runtime Error. Error: Cookies can only be modified in a Server Action or Route Handler." I ...

When iteratively utilizing the setValue() function, an unintentional occurrence of an 'Uncaught error' is encountered

I encountered an issue while trying to update a spreadsheet upon submitting a form. The problem is that after pressing the submit button, the remaining commands are not being executed properly. As a result, I see an error message in the console saying "U ...

Encountering a timeout issue with the Sinch API within an Angular 2 project during the onCallProgressing

We successfully integrated Sinch into our angular 2 web application. Most functionalities are working perfectly, except for the user calling feature using the sinch phone demo. When the application is in the foreground, the call rings and connects withou ...

Techniques for incorporating a variable into the value field in JavaScript

let y = data[1]; cell1.innerHTML ='<input id="text" type="text" value= "'y'"/>' ; This snippet of code does not render any content when attempting to pass the variable, but if you provide a specific value like "h", it will displa ...

Manage responses from ajax submission

My settings form has a unique feature to prevent users from making changes by mistake. After completing the form, users click the save button to trigger a modal (using Bootstrap modals) asking for their password before processing the original form. If the ...

Is there a way to retrieve the left offset of a floating element even when it is positioned outside the viewport?

My current situation involves creating several panels that are stacked side by side within a main container. Each panel takes up 100% of the viewport width and height. I want to be able to horizontally scroll to each panel when clicking on their respective ...

Access information stored within nested JSON objects on a local server

After creating a test page, this is the structure that I have set up: <!DOCTYPE html> <html lang="en" class="no-js"> <head> <title>Get JSON Value</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/ ...

Is there a way for me to create a clickable link from a specific search result retrieved from a MySQL database using an AJAX

Currently, I am attempting to create an ajax dropdown search form that provides suggestions based on results from a MySQL database. The goal is for the user to be able to click on a suggestion and be redirected to the specific product. The code I am using ...

Restangular is throwing an error because it cannot find the reference for _

I encountered an issue with Restangular where I'm getting the error message: Uncaught ReferenceError: _ is not defined from restangular when trying to use it. Code Snippet: <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angula ...

Tips for maintaining the state in a React class component for the UI while navigating or refreshing the page

Is there a way to persist the selection stored in state even after page navigation? I have heard that using local storage is a possible solution, which is my preferred method. However, I have only found resources for implementing this in functional compone ...

Is there a way to retrieve the ID by using the autocomplete feature to search for a user's first name and last name in PHP

Check out this code from index.php (all credit to the original owner): <HTML> <HEAD> <TITLE> Ajax php Auto Suggest </TITLE> <link href="css/style.css" rel="stylesheet" type="text/css"> <SCRIPT LANGUAGE="JavaScript ...