weixin_33721344 2017-11-27 14:51 采纳率: 0%
浏览 33

jQuery验证AJAX表单

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();
      }
    })
}
  • 写回答

1条回答 默认 最新

  • weixin_33696822 2017-11-27 14:52
    关注

    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.

    评论

报告相同问题?