Code Rider
Code Rider

Reputation: 2063

jquery ajax is not returning back to success function from MVC Controller

I'm hitting a method in controller from jquery ajax. I have an html page outside the application from where I'm calling this method.

Below is the ajax code written on html page.

function SignIn() {
        var d = JSON.stringify({
            Email: $('#email').val(),
            Password: $('#password').val()
        });

        $.ajax({
            url: "http://localhost:58954/Account/SignIn",
            type: "POST",
            contentType: "application/json; charset=utf-8",
            dataType: "JSON",
            data: d,
            success: function (e) {
                alert('success');

            },
            error: function (e) {
                alert(JSON.stringify(e));
            }
        });
    }

Below is the code written in controller's method. I'm returning Json object from here.

[AjaxOnly(), HttpPost(), AllowAnonymous()]
    public ActionResult SignIn(AuthenticationModel model)
    {

     // here code written for authentication 

      dynamic jsonData = new {
            Message = errorMessage,
            HasError = HasError,
            RedirectUrl = redirectUrl
        };

        return Json(jsonData);
    }

When ajax code run then it first goes to error function and shows me following details in alert.

enter image description here

After this it hits the method in controller and code runs perfectly as it should and after that it doesn't return back to ajax call's success function.

It shows the Json object on page as below:

Upvotes: 0

Views: 1153

Answers (2)

MaNi
MaNi

Reputation: 1

  1. check if signin method is in document.ready function
  2. if synchronous call is needed then you can use 'async': false
  3. controller signin method expects AuthenticationModel as input parameter hence check ajax method returns the expected object, else try as string parameters in controller
  4. as per the above controller code it always return jsondata which always returns error object in it.

Upvotes: 0

PratikSatikunvar
PratikSatikunvar

Reputation: 181

I have doubt in the way you are passing the data.

Try to pass the data without doing stringify and see if it works.

Upvotes: 1

Related Questions