0

I have a doubt with the json ajax call in MVC. I created a form for login, in that username, password and login button

and added a js file for login and a controller with httpPost type. whats my problem is when I click the login button it goes to the login js file click event and execute the ajax call to the controller and the controller returns the JSON result as success but on the ajax response the page gets refreshed and executed the login Index action method and another strange thing is if I again click the login then the ajax call response coming correctly as JSON(data.success)

Can anyone help me to sort out!.

script(executes through the button click event):

    function login() {
    var errorLabel = $("#error");
    var email = $("#email").val();
   var password = $("#password").val();
   var rememberMe = $("#rememberMe:checked").length > 0;
   displayLoadingSpinner(true);
  displayLoginButton(false);
  if (email === "" || password === "") {
    errorLabel.text("Please fill all fields");
    errorLabel.show();
    displayLoadingSpinner(false);
    displayLoginButton(true);
   } else {
    $.ajax({
        type: "POST",
        cache: false,
        url: "/Login/Login",
        data: { "username": email, "password": password, "rememberMe": 
               rememberMe },
        success: function(data) {
            if (data.Success === true) {
                if (data.IsExistingUserRecurringPayment === true) {
                    window.location = "/dashboard";
            } else {

                if (data.Message === "") {
                    errorLabel.text("Incorrect Username or Password");
                } else {
                    errorLabel.text(data.Message);
                    displayLoadingSpinner(false);
                    displayLoginButton(true);
                }
                errorLabel.show();
            }
        },
        error: function() {
            errorLabel.text("Unable to validate given credentials");
            errorLabel.show();
            displayLoadingSpinner(false);
            displayLoginButton(true);
        }
    });
}
 }

Controller:

[HttpPost]
    public JsonResult Login(string username, string password, bool rememberMe = false)
    {
        AssertHelper.AssertNotNull(username, "username");
        AssertHelper.AssertNotNull(password, "password");

        try
        {
            var result = _authenticationService.Login(username, password, rememberMe);
            if (result.Success)
            {
                Session["CurrentUser"] = CurrentUser;
                return Json(new { Success = true }, "application/json", JsonRequestBehavior.AllowGet);
            }
            else
            {
                var errorMessage = string.IsNullOrEmpty(result.Message)
                    ? "Incorrect Username or Password"
                    : result.Message;
                return Json(new { Success = false, Message = errorMessage }, "application/json", JsonRequestBehavior.AllowGet);
            }
        }
        catch (Exception ex)
        {
            Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
            return Json(new { Success = false, Message = ex.Message }, "application/json", JsonRequestBehavior.AllowGet);
        }
    }

In View:

<form class="form_fields" onsubmit="return false;">
                        <div class="form-group">
                            <input type="text" class="form-control" id="txtUserName" placeholder="UserName">
                        </div>
                        <div class="form-group">
                            <input type="password" class="form-control" id="password" placeholder="Password">
                        </div>
                        <p style="color: red; display: none" id="error"></p>
                        <button type="submit" class="btn_full btn_blue" id="btnLogin">Log in</button>
                        <div class="lds-ripple" style="display:none;"><div></div><div></div></div>
                        <div class="spinner" style="display: none;">
                            <div class="bounce1"></div>
                            <div class="bounce2"></div>
                            <div class="bounce3"></div>
                        </div>
                    </form>

1 Answers1

1

Looks like the issue could be that the button being pressed is triggering both your java-script "login()" function and also the form's "submit" event (which is what is causing the refresh). Here are two ways you could prevent the refresh:

Try changing the button html so that it doesn't cause a submit event by changing the button type from "submit" to "button"

Or

Listen for the submission event and prevent default behavior e.g. e.preventDefault(). How to do this is explained well here

Sam
  • 46
  • 7