The following javascript code works with the facebook login window appearing and allowing a user to login. The response values are captured and I know it works as alerts appear where setup but I cannot pass the value back to a controller method.
#RequestMapping(value ="/getAccessToken" , method = RequestMethod.POST)
public #ResponseBody String getAccessToken(#RequestBody String token){
System.out.println(token);
return token;
}
Javascript method called:
function doLogin() {
FB.login(function(response) {
alert(response);
console.log(response);
if (response.authResponse) {
alert(response.authResponse.userID);
alert(response.authResponse.accessToken);
var Token = response.authResponse.accessToken;
alert(Token);
$.ajax({
type: "POST",
url: "/HelloController/getAccessToken",
data: Token,
success: function (result) {
alert("Token");
},
error: function (result) {
alert("oops");
}
});
document.getElementById('loginBtn').style.
display = 'none';
getUserData();
}}, {perms:'manage_pages',
scope: 'email,public_profile', return_scopes: true});
};
The error I get is the following:
WARN 25660 --- [nio-8080-exec-9]
o.s.web.servlet.PageNotFound :
Request method 'POST' not supported
Appreciate responses.
The problem could be that you are using a new version of JQuery that sends request data as post form data instead of JSON as default. Try changing your ajax call to the following. The form data would not be recognized by your controller so if this is the case you should see a 404.
$.ajax({
type: "POST",
traditional: true,
url: "/HelloController/getAccessToken",
data: JSON.stringify(Token),
success: function (result) {
alert("Token");
},
error: function (result) {
alert("oops");
}
});
For reference see this post: Send JSON data via POST (ajax) and receive json response from Controller (MVC)
Related
I'm trying to get user email from ASP.NET Web API through writing an email in an input box using JQuery (to select message recipients), But the returned value is null. Are there any problems in passing process in my code?
Web API:
[AllowAnonymous]
[HttpGet]
[Route("get-reciver-email")]
public ApplicationUser GetReciverEmailId([FromUri] string email)
{
return _userManager.FindByEmail(email);
}
Client-side "JQuery":
$('#toEmail').keyup(function () {
$.ajax({
url: '/api/Account/get-reciver-email/' + $("#toEmail").val(),
method: 'GET',
success: function (response) {
console.log(response);
},
// Display errors if any in the Bootstrap alert <div>
error: function (jqXHR) {
$('#divErrorText').text(jqXHR.responseText);
$('#divError').show('fade');
}
});
});
I expect to return user info based on passed email in HTML form.
Solved.
I removed [FromUri] & I used query-string (THX for #Mihai), also I modified API function to the following:
[AllowAnonymous]
[HttpGet]
[Route("get-reciver-email")]
public string GetReciverEmailId(string email)
{
return db.Users.Where(x => x.Email == email).Select(x => x.Id).Single();
}
Client-side code:
$('#toEmail').keyup(function () {
$.ajax({
url: '/api/Account/get-reciver-email/?email=' + $("#toEmail").val(),
method: 'GET',
success: function (response) {
console.log(response);
},
// Display errors if any in the Bootstrap alert <div>
error: function (jqXHR) {
$('#divErrorText').text(jqXHR.responseText);
$('#divError').show('fade');
}
});
});
I would like to call a code behind function from the client side.
The function cannot be static - should modified unstatic variabels.
I was able to create a non-visible button, and when I need that function I demonstrate a click on that btn.
How can I send parameters to that code behind function?
$.ajax({
url: '/ControllerName/ActionName',
type: "GET",
data: { param1: val1 },
success: function (res) {
alert(res) // res is results that came from function
}
});
This is the client side to call backend method. The server side to accept this request:
public ActionResult ActionName(string param1)
{
return View(param1);
}
In this case, we used jQuery, the javascript plugin, and we used AJAX request, also sending parameters.
Using MVC and jQuery
Client Side ( Using Razor )
$.ajax({
url: '#Url.Action("ActionName","ControllerName",new{parameters})',
type: "GET",
contentType: "application/json",
data: { param1: val1 },
success: function (res) {
alert(res) // res is results that came from function
},
error: function (jqXHR, error, errorThrown) {
console.log('An error as occured');
},
});
Server Side
[HttpGet]
public JsonResult ActionName(string param1)
{
return Json(param1, JsonRequestBehavior.AllowGet);
}
Note: HttpGet Verb is the default verb for every ActionResult/JsonResult
the button have a CommandArgument attribute that you can use to send a value to that function and you can read it as follow :
public void yourFunction(object sender,Eventargs e)
{
string args = ((LinkButton)sender).CommandArgument.ToString();
// rest of code here
}
I wrote a JQuery script to do a user login POST (tried to do what I have done with C# in the additional information section, see below).
After firing a POST with the JQuery code from my html page, I found the following problems:
1 - I debugged into the server side code, and I know that the POST is received by the server (in ValidateClientAuthentication() function, but not in GrantResourceOwnerCredentials() function).
2 - Also, on the server side, I could not find any sign of the username and password, that should have been posted with postdata. Whereas, with the user-side C# code, when I debugged into the server-side C# code, I could see those values in the context variable. I think, this is the whole source of problems.
3 - The JQuery code calls function getFail().
? - I would like to know, what is this JQuery code doing differently than the C# user side code below, and how do I fix it, so they do the same job?
(My guess: is that JSON.stringify and FormURLEncodedContent do something different)
JQuery/Javascript code:
function logIn() {
var postdata = JSON.stringify(
{
"username": document.getElementById("username").value,
"password": document.getElementById("password").value
});
try {
jQuery.ajax({
type: "POST",
url: "http://localhost:8080/Token",
cache: false,
data: postdata,
dataType: "json",
success: getSuccess,
error: getFail
});
} catch (e) {
alert('Error in logIn');
alert(e);
}
function getSuccess(data, textStatus, jqXHR) {
alert('getSuccess in logIn');
alert(data.Response);
};
function getFail(jqXHR, textStatus, errorThrown) {
alert('getFail in logIn');
alert(jqXHR.status); // prints 0
alert(textStatus); // prints error
alert(errorThrown); // prints empty
};
};
Server-side handling POST (C#):
public override async Task ValidateClientAuthentication(
OAuthValidateClientAuthenticationContext context)
{
// after this line, GrantResourceOwnerCredentials should be called, but it is not.
await Task.FromResult(context.Validated());
}
public override async Task GrantResourceOwnerCredentials(
OAuthGrantResourceOwnerCredentialsContext context)
{
var manager = context.OwinContext.GetUserManager<ApplicationUserManager>();
var user = await manager.FindAsync(context.UserName, context.Password);
if (user == null)
{
context.SetError(
"invalid_grant", "The user name or password is incorrect.");
context.Rejected();
return;
}
// Add claims associated with this user to the ClaimsIdentity object:
var identity = new ClaimsIdentity(context.Options.AuthenticationType);
foreach (var userClaim in user.Claims)
{
identity.AddClaim(new Claim(userClaim.ClaimType, userClaim.ClaimValue));
}
context.Validated(identity);
}
Additional information: In a C# client-side test application for my C# Owin web server, I have the following code to do the POST (works correctly):
User-side POST (C#):
//...
HttpResponseMessage response;
var pairs = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>( "grant_type", "password"),
new KeyValuePair<string, string>( "username", userName ),
new KeyValuePair<string, string> ( "password", password )
};
var content = new FormUrlEncodedContent(pairs);
using (var client = new HttpClient())
{
var tokenEndpoint = new Uri(new Uri(_hostUri), "Token"); //_hostUri = http://localhost:8080/Token
response = await client.PostAsync(tokenEndpoint, content);
}
//...
Unfortunately, dataType controls what jQuery expects the returned data to be, not what data is. To set the content type of the request data (data), you use contentType: "json" instead. (More in the documentation.)
var postdata = JSON.stringify(
{
"username": document.getElementById("username").value,
"password": document.getElementById("password").value
});
jQuery.ajax({
type: "POST",
url: "http://localhost:8080/Token",
cache: false,
data: postdata,
dataType: "json",
contentType: "json", // <=== Added
success: getSuccess,
error: getFail
});
If you weren't trying to send JSON, but instead wanted to send the usual URI-encoded form data, you wouldn't use JSON.stringify at all and would just give the object to jQuery's ajax directly; jQuery will then create the URI-encoded form.
try {
jQuery.ajax({
type: "POST",
url: "http://localhost:8080/Token",
cache: false,
data: {
"username": document.getElementById("username").value,
"password": document.getElementById("password").value
},
dataType: "json",
success: getSuccess,
error: getFail
});
// ...
To add to T.J.'s answer just a bit, another reason that sending JSON to the /token endpoint didn't work is simply that it does not support JSON.
Even if you set $.ajax's contentType option to application/json, like you would to send JSON data to MVC or Web API, /token won't accept that payload. It only supports form URLencoded pairs (e.g. username=dave&password=hunter2). $.ajax does that encoding for you automatically if you pass an object to its data option, like your postdata variable if it hadn't been JSON stringified.
Also, you must remember to include the grant_type=password parameter along with your request (as your PostAsync() code does). The /token endpoint will respond with an "invalid grant type" error otherwise, even if the username and password are actually correct.
You should use jquery's $.param to urlencode the data when sending the form data . AngularJs' $http method currently does not do this.
Like
var loginData = {
grant_type: 'password',
username: $scope.loginForm.email,
password: $scope.loginForm.password
};
$auth.submitLogin($.param(loginData))
.then(function (resp) {
alert("Login Success"); // handle success response
})
.catch(function (resp) {
alert("Login Failed"); // handle error response
});
Since angularjs 1.4 this is pretty trivial with the $httpParamSerializerJQLike:
.controller('myCtrl', function($http, $httpParamSerializerJQLike) {
$http({
method: 'POST',
url: baseUrl,
data: $httpParamSerializerJQLike({
"user":{
"email":"wahxxx#gmail.com",
"password":"123456"
}
}),
headers:
'Content-Type': 'application/x-www-form-urlencoded'
})
})
I'm trying to get all my posts from the database to be displayed with the help of ajax or getjson but can't get it to work. Using mvc web api and I have a view where I want to display it. There is a method working called post so nothing wrong with my routing etc.
Code for my views js-script, I want to display all posts with the help of my mvc api controller and ajax in a div called #userMessage.
$(document).ready(function() {
$('#btnGetPosts').click(function() {
jQuery.support.cors = true;
var recieverID = $('#RecieverID').val();
$.ajax({
url: "/api/Posts/GetPosts" ,
//data: (?)
type: "GET",
dataType: "jsonp",
error: function(request, status, error) {
alert(request.responseText);
},
success: function(data) {
alert(data);
}
});
});
});
my controller method to get all the posts
// GET: api/Posts
public IEnumerable<Post> GetPosts()
{
//querystring is made to get the recieverID, it's also reachable in the view. //("#RecieverID")
string querystring = HttpContext.Current.Request.QueryString["Username"];
// Converts Username querystring to a user-id
int id = UserRepository.GetUserId(querystring);
// uses linq to get a specific user post (all posts)
var userPost = PostRepository.GetSpecificUserPosts(id);
return userPost;
}
my PostRepository.GetSpecifiedUserPosts method in my repository
public List<Post> GetSpecificUserPosts(int user)
{
using (var context = new DejtingEntities())
{
var result = context.Posts
.Where(x => x.RecieverID == user)
.OrderByDescending(x => x.Date)
.ToList();
return result;
}
Try this
$(document).ready(function() {
$('#btnGetPosts').click(function() {
jQuery.support.cors = true;
var recieverID = $('#RecieverID').val();
$.ajax({
url: "/api/Posts/Posts" ,
data: {
username: recieverID
},
type: "GET",
dataType: "jsonp",
error: function(request, status, error) {
alert(request.responseText);
},
success: function(data) {
alert(data);
}
});
});
});
and in code behind,
public IEnumerable<Post> GetPosts(string username)
{
// Converts Username querystring to a user-id
int id = UserRepository.GetUserId(username);
// uses linq to get a specific user post (all posts)
var userPost = PostRepository.GetSpecificUserPosts(id);
return userPost;
}
You use wrong url. Try send ajax request to '/api/Posts'.
Also you can add routing attribute to the action [Route('/api/Posts/GetPosts')] and send request to '/api/Posts/GetPosts'.
See Calling the Web API with Javascript and jQuery and Routing in ASP.NET Web API.
I got some problem while posting JSON data into MVC 4 controller.
Below method is working fine in Firefox but unfortunately failed in IE 9
The JavaScript :
var newCustomer = {
CustName: $("#CustName").val(),
CustLocalName: $("#CustLocalName").val(),
CustNumber: $("#CustNumber").val(),
CountryID: $("#SelectCountry").val(),
City: $("#City").val()
};
$.ajax({
url: '#Url.Content("~/CustomerHeader/CreateCustomerHeader")',
cache: false,
type: "POST",
dataType: "json",
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(newCustomer),
success: function (mydata) {
$("#message").html("Success");
},
error: function () {
$("#message").html("Save failed");
}
});
and this is my controller :
public JsonResult CreateCustomerHeader(CustomerHeader record)
{
try
{
if (!ModelState.IsValid)
{
return Json(new { Result = "ERROR", Message = "Form is not valid! Please correct it and try again." });
}
RepositoryHeader.Update(record);
return Json(new { Result = "OK", Record = record});
}
catch (Exception ex)
{
return Json(new { Result = "ERROR", Message = ex.Message });
}
}
the "data" variable as in public JsonResult CreateCustomerHeader(CustomerHeader **data**) is getting NULL but while using FireFox it holds the correct value.
UPDATE : New method trying using $.post
function CreateNewCustomer(newCustomer) {
$.post("/CustomerHeader/CreateCustomerHeader",
newCustomer,
function (response, status, jqxhr) {
console.log(response.toString())
});
}
Based off the bit that you've shown, this is a simplified variation that may work more consistently, using jQuery.post() (http://api.jquery.com/jQuery.post/):
var data = {
CustName: $("#CustName").val(),
CustLocalName: $("#CustLocalName").val(),
CustNumber: $("#CustNumber").val(),
CountryID: $("#SelectCountry").val(),
City: $("#City").val()
};
$.post({
'#Url.Action("CreateCustomerHeader", "CustomerHeader")',
data,
function(response, status, jqxhr){
// do something with the response data
}).success(function () {
$("#message").html("Success");
}).error(function () {
$("#message").html("Save failed");
});
$.post() uses $.ajax as it's base, but abstracts some of the details away. For instance, $.post calls are not cached, so you don't need to set the cache state (and setting it is ignored if you do). Using a simple JavaScript object lets jQuery decide how to serialize the POST variables; when using this format, I rarely have issues with the model binder not being able to properly bind to my .NET classes.
response is whatever you send back from the controller; in your case, a JSON object. status is a simple text value like success or error, and jqxhr is a jQuery XMLHttpRequest object, which you could use to get some more information about the request, but I rarely find a need for it.
first of all I would like to apologize #Tieson.T for not providing details on JavaScript section of the view. The problem is actually caused by $('#addCustomerHeaderModal').modal('hide') that occurred just after ajax call.
The full script :
try{ ..
var newCustomer =
{
CustName: $("#CustName").val(),
CustLocalName: $("#CustLocalName").val(),
CustNumber: $("#CustNumber").val(),
CountryID: $("#SelectCountry").val(),
City: $("#City").val()
};
$.ajax({
url: '/CustomerHeader/CreateCustomerHeader',
cache: false,
type: "POST",
dataType: "json",
data: JSON.stringify(newCustomer),
contentType: "application/json; charset=utf-8",
success: function (mydata) {
$("#message").html("Success");
},
error: function () {
$("#message").html("Save failed");
}
});
}
catch(Error) {
console.log(Error.toString());
}
//$('#addCustomerHeaderModal').modal('hide')//THIS is the part that causing controller cannot retrieve the data but happened only with IE!
I have commented $('#addCustomerHeaderModal').modal('hide') and now the value received by controller is no more NULL with IE. Don't know why modal-hide event behave like this with IE9.
Thanks for all the efforts in solving my problem guys :-)