What I am supposed to return from a server-side method called by ajax? - ajax

I have the following jQuery script:
$(document).ready(function() {
$("#resendActivationEmailLink").bind("click", function(event) {
$.get($(this).attr("href"), function() {
$("#emailNotActivated").html("<span>not yet activated. email sent!</span>");
}, "html");
event.preventDefault();
});
});
Basically, when a user clicks a link the following server-side method is invoked:
#RequestMapping(value = "/resendActivationEmail/{token}", method = RequestMethod.GET, produces = "application/json")
public #ResponseBody
String resendActivationEmail(#PathVariable("token") String token) {
preferencesService.resendActivationEmail(token);
return "dummy";
}
and some business logic is executed on the server but there is no real outcome from the server to be used on the client/browser side apart from an ajax success or an ajax failure.
Now what I am really not sure about is what my server-side method is supposed to return!
Currently it just returns the string dummy but of course this is only temporary. Should I go for no return type (void) or null or something else??
Note that I can change the datatype parameter of the jQuery get method.
EDIT:
I have altered my server-side method as follows:
#RequestMapping(value = "/resendActivationEmail/{token}", method = RequestMethod.GET)
public #ResponseBody void resendActivationEmail(#PathVariable("token") String token) {
preferencesService.resendActivationEmail(token);
}
#ResponseBody is required because this is an ajax call.

There is no point in returning a dummy value in this case. If you are not doing anything with the return value, then you can just do something like this:
#RequestMapping(value="/resendActivationEmail/{token}", method=RequestMethod.GET)
#ResponseStatus(org.springframework.http.HttpStatus.NO_CONTENT)
public void resendActivationEmail(#PathVariable String token) {
preferencesService.resendActivationEmail(token);
}
There will be a 204 response code instead of a 200 but that should be fine.

I'm assuming you are returning JSON from the server (from your server code: produces = "application/json").
Since you don't care about what gets returned, i.e. you are not handling the return value in your callback function, after $.get, then you can just return "{}", or if you want to handle the response you can go with something like:
{ "success": true }
// or
{ "error": "Error messages here" }

Related

Listen to input field using a spring controller

Is it possible, in our controller, to get realtime input from a user writing in a html textfield? I know its possible to do via eg. jquery/js, but we are students and want a java'ish solution.
only using java is impossible because java need communication with the HTML page, you can perform that but you need to use java-script too. for example you can write a controller and call it using Ajax in a event java-script method like keyup.
#RestController
#RequestMapping("/info/")
public class Controller {
#RequestMapping(value="/get/",
method=RequestMethod.POST,
produces=MediaType.APPLICATION_JSON_VALUE,
consumes=MediaType.APPLICATION_JSON_VALUE)
public Map<String,Object> getInputData(#RequestBody Map<String, Object> data){
String inputData = data.get("inputValue").toString();
//TODO
return data;
}
}
from java-script build your Json response and call /info/get/ rest URL.
for example using axios.
axios.post('/info/get/', {
inputValue: 'your input form data'
})
.then(function (response) {
//todo
})
.catch(function (error) {
// if has errors
});
but otherwise can't be

Update data with Microsoft.AspNet.WebApi

Hey i am having a big trouble updating data in my client side REST application.
I made a Web API controller.
// PUT: api/Contacts/5
[ResponseType(typeof(void))]
public IHttpActionResult PutContact(Contact contact, int id)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (id != contact.ContactId)
{
return BadRequest();
}
_contactService.Update(contact);
return StatusCode(HttpStatusCode.NoContent);
}
And also client side service method:
public async Task<T> PutData<T>(T data, int dataId)
{
HttpResponseMessage resp = await this._client.PutAsJsonAsync(_serviceUrl + "/" + dataId, data);
resp.EnsureSuccessStatusCode();
return await resp.Content.ReadAsAsync<T>();
}
Service URL shows in debug mode that i goes to endpoint:
http://localhost:21855/api/Contacts/8
But it does not even go to breakpoint when i debug my server controller PutContact method.
What i am doint wrong? I need to update the data but i cant, because my client-side application won't even go to servers breakpoint on debug mode!!!
It gives me an error response 405 : Method not allowed
You can't have two different body parameters in the same method.
What you need to do is to set the id parameter to come from the URI and the Contact parameter from the body, like this:
public IHttpActionResult PutContact([FromBody]Contact contact, [FromUri]int id)
{
// method code
}
BTW, I suppose you have a GET method in your controller which looks like this:
public IHttpActionResult GetContact(int id)
{
// method code
return Contact; // pseudo-code
}
The error you getting comes from the fact that the system is not really calling your PUT method but the GET one (the system is ignoring the Contact parameter for the reason I expressed before): calling a GET method with a PUT verb results in a 405 Method Not Allowed exception.

Posting to Web Api parameters are null

I have a jquery method which looks like this:
$.post("/api/amazon/signature", { "policy": policy }, function (data) {
console.log(data);
});
the api method looks like this~:
// POST api/amazon/signature
[HttpPost]
[Route("api/amazon/signature")]
public IHttpActionResult GetSignature([FromBody]string policy)
{
var bKey = Encoding.ASCII.GetBytes(ConfigurationManager.AppSettings["AWSSecretKey"]);
var hmacSha1 = new HMACSHA1(bKey);
var bPolicy = Encoding.ASCII.GetBytes(policy);
var hash = hmacSha1.ComputeHash(bPolicy);
var encoded = Convert.ToBase64String(hash);
return Ok(encoded);
}
but when I run this code policy is always null!
If I change my method to this:
public class Signature
{
public string Policy { get; set; }
}
// POST api/amazon/signature
[HttpPost]
[Route("api/amazon/signature")]
public IHttpActionResult GetSignature([FromBody]Signature model)
{
var bKey = Encoding.ASCII.GetBytes(ConfigurationManager.AppSettings["AWSSecretKey"]);
var hmacSha1 = new HMACSHA1(bKey);
var bPolicy = Encoding.ASCII.GetBytes(model.Policy);
var hash = hmacSha1.ComputeHash(bPolicy);
var encoded = Convert.ToBase64String(hash);
return Ok(encoded);
}
and modify my jquery to this:
$.post("/api/amazon/signature", { "Policy": policy }, function (data) {
console.log(data);
});
it works fine....
Can someone tell me why?
ASP.NET Web API binds the request body in its entirety to one parameter (one parameter only and not more). By default, body is bound to a complex type. So, when you change the parameter type to Policy which is a complex type, you don't need to actually specify FromBody. Also binding works correctly now because you are sending JSON Object which looks something like this { "policy": policy }. Web API has no trouble in binding JSON object to your complex type.
When it comes to a simple type, string in your case, you must specify FromBody, since by default Web API binds from URI path and query string. In that case however, you cannot send a JSON Object. Web API is going to bind the entire body to that parameter, which is string. So, the request body must be just a string like this - "ABC123" and not a JSON object. If you send just "ABC123" (including the quotes) in the request body, your string parameter will be populated with ABC123.

How To Pass formdata parameters into ASP.NET WebAPI without creating a record structure

I have data coming into my form that looks like the image below (sessionsId: 1367,1368).
I've create c# in my webapi controller that works as below. when I've tried ot just make use SessionIds as the parameter (or sessionIds) by saying something like PostChargeForSessions(string SessionIds) either null gets passed in or I get a 404.
What is the proper way to catch a form parameter like in my request without declaring a structure.
(the code below works, but I'm not happy with it)
public class ChargeForSessionRec
{
public string SessionIds { get; set; }
}
[HttpPost]
[ActionName("ChargeForSessions")]
public HttpResponseMessage PostChargeForSessions(ChargeForSessionRec rec)
{
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, new ShirtSizeReturn()
{
Success = true,
//Data = shirtSizeRecs
});
return response;
}
You can declare the action method like this.
public HttpResponseMessage Post(string[] sessionIds) { }
If you don't want to define a class, the above code is the way to go. Having said that, the above code will not work with the request body you have. It must be like this.
=1381&=1380

mvc webapi cross domain post [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
CORS with WebAPI for XmlHttpRequest
I'm trying to implement cross-domain ajax post to my webApi project. I had few troubles with that:
1. I always was getting 204 error until changed my webapi action from
public void submit(Submission model)
to
public bool submit(Submission model)
don't know why, but now I'm getting 200 OK status
2. Still my ajax firing error callback.
3. Long time ago I solved this kind of error of cross-domain posting by adding
HttpContext.Response.AddHeader("Access-Control-Allow-Origin", "*");
to my controller. But now in webApi i'm inherent from : ApiController and this trick doesn't work. Shows me compiler Error an object reference is required for the non-static field, method, or property"System.Web.HttpContext.Response.get"
I have tryed to post via dataType: 'JSONP' but I get null model.
Here goes Javascript request:
var model = {
"type": $("#model-type").val(),
"subject": $("#subject-text").val(),
"body": $("#body-text").val()
};
$.ajax({
type: "POST",
dataType: 'JSONP',
url: $("#submit-url").val(),
data: model,
success: function () {
alert("Succesfully submitted");
},
error: function () {
alert("Error...");
}
});
What I'm doing wrong?
SOLVED
Thanks to everybody for helping me out. I found solution in one of the comment links. I used following approach, which I find pretty simple.
Source:
Implementing CORS support in ASP.NET Web APIs
What I made:
1. Created new Class in my project: CorsHandler.cs and just copy-pasted following code:
public class CorsHandler : DelegatingHandler
{
const string Origin = "Origin";
const string AccessControlRequestMethod = "Access-Control-Request-Method";
const string AccessControlRequestHeaders = "Access-Control-Request-Headers";
const string AccessControlAllowOrigin = "Access-Control-Allow-Origin";
const string AccessControlAllowMethods = "Access-Control-Allow-Methods";
const string AccessControlAllowHeaders = "Access-Control-Allow-Headers";
protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
bool isCorsRequest = request.Headers.Contains(Origin);
bool isPreflightRequest = request.Method == HttpMethod.Options;
if (isCorsRequest)
{
if (isPreflightRequest)
{
return Task.Factory.StartNew(() =>
{
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
response.Headers.Add(AccessControlAllowOrigin, request.Headers.GetValues(Origin).First());
string accessControlRequestMethod = request.Headers.GetValues(AccessControlRequestMethod).FirstOrDefault();
if (accessControlRequestMethod != null)
{
response.Headers.Add(AccessControlAllowMethods, accessControlRequestMethod);
}
string requestedHeaders = string.Join(", ", request.Headers.GetValues(AccessControlRequestHeaders));
if (!string.IsNullOrEmpty(requestedHeaders))
{
response.Headers.Add(AccessControlAllowHeaders, requestedHeaders);
}
return response;
}, cancellationToken);
}
else
{
return base.SendAsync(request, cancellationToken).ContinueWith(t =>
{
HttpResponseMessage resp = t.Result;
resp.Headers.Add(AccessControlAllowOrigin, request.Headers.GetValues(Origin).First());
return resp;
});
}
}
else
{
return base.SendAsync(request, cancellationToken);
}
}
}
Opened my Global.asax and modifyed Application_Start :
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
GlobalConfiguration.Configuration.MessageHandlers.Add(new CorsHandler());
}
Pay attention to the last line in action.
This approach is compatible with MVC3 and .NET 4.0. Works great, now I can handle "success" and "error" callbacks in ajax.
Answers to your questions respectively:
Status 204 is not an error, which means no content to return but everything's good. Here's the definition of 204 in RFC2616
10.2.5 204 No Content
The server has fulfilled the request but does not need to return an
entity-body, and might want to return updated metainformation. The
response MAY include new or updated metainformation in the form of
entity-headers, which if present SHOULD be associated with the
requested variant.
If the client is a user agent, it SHOULD NOT change its document view
from that which caused the request to be sent. This response is
primarily intended to allow input for actions to take place without
causing a change to the user agent's active document view, although
any new or updated metainformation SHOULD be applied to the document
currently in the user agent's active view.
The 204 response MUST NOT include a message-body, and thus is always
terminated by the first empty line after the header fields.
Could you articulate what's the error you met? The ASP.NET Web API currently doesn't have a JSONP formatter out of box. Here's some 3rd part implementation:
http://www.west-wind.com/weblog/posts/2012/Apr/02/Creating-a-JSONP-Formatter-for-ASPNET-Web-API
http://www.nuget.org/packages/WebApi.JsonP
I hope they're helpful.
In Web API the way in which you refers to an Response is not through HttpContext. There are multiple ways to access.
The first option is to define action return HttpResponse directly.
public HttpResponseMessage Get(int id)
{
var response = this.Request.CreateResponse();
response.StatusCode = HttpStatusCode.OK;
response.Headers.Add("Access-Control-Allow-Origin", "*");
return response;
}
The second option is to use ActionFilter:
// define action filter for cross domain
public class CrossDomainActionFilter : ActionFilterAttribute
{
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
bool needCrossDomain = true;
if (needCrossDomain)
{
actionExecutedContext.Response.Headers.Add("Access-Control-Allow-Origin", "*");
}
base.OnActionExecuted(actionExecutedContext);
}
}
// At Controller
// GET api/values/5
[CrossDomainActionFilter]
public string Get(int id)
{
return "value";
}
The last option is to use MessageHandler:
public class CrossDomainMessageHandler : DelegatingHandler
{
protected async override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken)
{
var response = await base.SendAsync(request, cancellationToken);
response.Headers.Add("Access-Control-Allow-Origin", "*");
return response;
}
}
If you want to send information to another domain from ajax then you need to use jsonp (note this only works with get requests not post requests). Another alternative (if you are in control of both domains) is to use ARR (application request routing) to trick the browser into thinking the request is local then using ARR to rewrite the request to another domain. Using this technique you can use simple ajax gets and posts like normal.

Resources