Reputation: 1430
I am trying to post data from input values from textBoxes to restful service via jQuery and ajax. But im unable to do it.
Here is my HTML code:
<!DOCTYPE html>
<html>
<head>
<title>Login Page</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
<script type="text/javascript" src="LoginHtml.js">
</script>
</head>
<body>
<div id="registration">
<h2>Login Account</h2>
<form id="registerUserForm">
<fieldset>
<p>
<input id="txtUserName" type="text" required="required" autofocus="true" placeholder="User Name" />
</p>
<p>
<input id="txtPassword" type="password" required="required" placeholder="Password" />
</p>
<p>
<input type="button" id="submitForm" autofocus="true" /><br>
<input type="button" value="Login" onclick="Call()" ></input>
</p>
</fieldset>
</form>
</div>
</body>
</html>
Here is my javascript code:
function Call() {
jQuery.support.cors = true;
var data = {};
data.uid = document.getElementById('txtUserName');
data.pwd = document.getElementById('txtPassword');
$.ajax({
data: jQuery.toJSON(data),
dataType: "json",
url: "http://:xxxxxx:8080/Service1/Login",
type: "GET",
contentType: "application/json; charset=utf-8",
success: function (result) {alert("success");
alert(result.d);}
error: function OnError(request, result, error) {
alert(result);
}
});
Here is my code for service:
[WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Wrapped, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
public UserProfile Login(string uid, string pwd)
{
UserProfile oUser = null;
//UserDao userDao;
using (UserProfileDataContext db = new UserProfileDataContext())
{
var u = db.Users.FirstOrDefault(o => o.Username == uid && o.Password == pwd);
if (u != null)
{
oUser = new UserProfile();
oUser.Id = u.Id;
oUser.Username = u.Username;
oUser.Password = u.Password;
oUser.Email = u.Email;
}
}
return oUser;
}
Tell me where I am wrong.
Upvotes: 0
Views: 2444
Reputation: 279
I think you make a mistakes in your code. your writing service is "post" and you call this using "GET". so please change this.
[WebGet(BodyStyle = WebMessageBodyStyle.Wrapped, ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
Upvotes: 2
Reputation: 770
try to return in Login method the following
return Json(new { Id = oUser.Id, Username = oUser.Username });
And then in Success function
success: function (result) {
alert("success");
alert(result.Id);
}
And of course type must be POST in ajax call
Upvotes: 0
Reputation: 1903
Try serializing your form:
var data = $("#registerUserForm").serialize();
And change type to POST rather than GET
So ...
$.ajax({
data: data,
url: "http://:xxxxxx:8080/Service1/Login",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (result) {
alert("success");
alert(result.d);
}
error: function OnError(request, result, error) {
alert(result);
}
});
Upvotes: 1