简体   繁体   中英

jQuery validation AJAX form

I'm trying to add validation to my ResetPassword function. validation its work fine, but I got another problem my ResetPassword function not going to work after I add validation.Can anyone direct me in the right direction? thx.

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 Adresse" required/>

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

    </form>
  </div>

</div>

ResetPassword & validation code:

function ResetPassword(e) {

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

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

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

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

The issue is because you're always exiting the function before you send the AJAX request due to your use of the return statement in both conditions of your if statement.

Change 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!');
    }
  })
}

Also note that I amended the logic to only show the successful email message after the request completes. Your current code can show the 'email sent' message to the user, even though there is still scope for the function to fail.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM