Sreeraj
Sreeraj

Reputation: 2434

Jquery Ajax Post always Error

Hi I have a simple and small page which is to submit some values and read the httpresponsemessage from Web Api. This is my HTML code:

<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>Data Client</title>
<script  src="http://code.jquery.com/jquery-1.10.1.min.js"> </script>
<script>
    $(document).ready(function () {
        $("#post").click(function () {
           // alert(document.forms["form1"]["user"]);
            $.ajax({
                type: "Post",
                url: 'http://localhost:1505/api/user/Login',
                data: $("#form1").serialize(),
               // datatype: "null",

            }).always(function (data, textStatus, jqXHR) { alert(jqXHR.serialize())});
        });
    });
</script>


</head>
<body>

<form id="form1">
    <p>
       User: <input type="text" name="user" />
    </p>
    <p>
    Password: <input type="password" name="password" />
    </p>
    <p>
        <input type="button" id="post" value="Login"  />
    </p>

</form>
</body>
</html>

This is the corresponding Action Method in my Web Api.

  public HttpResponseMessage Login(User user)
    {
        if (ModelState.IsValid)
        {
            var found = (from p in db.Users
                         where (p.user == user.user && p.password == user.password)
                         select p).FirstOrDefault();
            if (found == null)
            {
                return Request.CreateResponse(HttpStatusCode.NotFound);
            }
            HttpResponseMessage response2 = Request.CreateResponse(HttpStatusCode.Found);
            Token token = new Token();
            string resptok = token.Generate(user);
            response2.Headers.Add("Authorization_Token", resptok);
            return response2;
        }
        else
        {
            return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
        }


        }

I can not figure out why it always alerts "Error". I am using JSON serialization in api. Thank You for your concern in advance

Upvotes: 0

Views: 188

Answers (1)

Saravana Kumar
Saravana Kumar

Reputation: 836

You are serializing jqXHR object, you should serialize data to get the response data.

Upvotes: 1

Related Questions