Web service Spring ajax call - javascript

I'm trying to call a web service with ajax. The service is up, and it can shows the result on the RestClient on firefox, but, in mi application call, gives me Status error "Pending".
This is my simple web service.
#Controller
#RequestMapping("/hello")
public class HelloWs {
#RequestMapping(value= "/helloWorld", method = RequestMethod.GET, headers = "Accept=application/xml, application/json")
public #ResponseBody String HelloWorld() {
return "Hello Worldssss¡¡";
}
And this is my ajax call.
function hellowsfunction() {
$.ajax({
type: "GET",
url:"http://localhost:8080/ehCS-ui/rest/hello/helloWorld",
crossDomain: true,
dataType: "JSON",
headers : {Accept : "applicationjson","Access-Control-Allow-Origin" : "*"},
success: function(msg) {
var returnedData = jQuery.parseJSON(msg);
$("#lblResult")
.text(result)
.slideUp("hide", function() { $(this).slideDown("slow") });
},
error: function (e) {
$("#lblResult").removeClass("loading");
alert('failed:'+e);
console.log(e);
}
});
what is wrong? Ideas?¿ please help.
Thanks

Your #RequestMapping is wrong... you should not map based on Accept header like this. Instead you should use produces parameter.
#RequestMapping(value="/helloWorld", method=RequestMethod.GET,
produces={"application/xml", "application/json"})
Also your header in the JS is incorrect. Just remove their specification completely.

Related

Java, JS : Tomcat refusing to call this method, unsupported media type

I am working on a Spring-MVC application in which for this single method I am getting an error as Unsupported media type. None of the other methods have this problem. Any help would be nice. Thank you-.
Java Code :
#RequestMapping(value = "/setnotificationlevels")
public
#ResponseBody
boolean setNotificationLevels(#RequestParam("groupid") long groupid, #RequestBody GroupMembers member) {
System.out.println("Set notification levels is called. ");
return this.groupMembersService.setNotificationLevels(member, groupid);
}
JS code :
setEmailNotifications : function (groupid, settings){
return $.ajax({
url: "/setnotificationlevels?groupid=" + groupid,
type: 'POST',
cache:false,
data : JSON.stringify(settings),
contentType: "application/json; charset=utf-8"
});
},
Error log :
description The server refused this request because the request entity is in a format not supported by the requested resource for the requested method.
Thank you.
tell your java code that its a post or get http methd:
#RequestMapping(value = url, method = RequestMethod.POST)
public#ResponseBody StringOrAnyResponseObject fName(#RequestBody final Object o)
{}
and in your js:
in any function
return $http.post(url,parameterMap);
Try to add consumes = "application/json;charset=UTF-8" to #RequestMapping annotation.

angularjs$http.get and java api call

I'm trying to make an angularjs $http.get request with parameters but it's not working due to syntaxt may be. Can you please
confirm what i'm doing wrong , maybe syntax is wrong in angularjs call or in java api method
$http.get(document.requestPathPrefix + "/home/my-api",
$scope.requestParametersObject
).then(
function(response) {
$scope.output = response.data;
},
function(response) {
$scope.retrieveErrorMssg = "Failed to retrieve required data.";
});
my parameters are like in this image
parameter object for api call
And in java api call like this
#RequestMapping(value = "/my-api", method = RequestMethod.GET)
public ResponseEntity<Collection<MyObjectResponse>> getMyObjResponse(#RequestBody final MyObjectRequest request)
{
Map<Integer,MyObjectResponse> oResponse = new HashMap<>();
try {
//Manipulation and db calls
} catch (Exception e) {
log.error(e.getMessage(), e);
}
return new ResponseEntity<Collection<MyObjectResponse>>(oResponse.values(), HttpStatus.OK);
}
try ,
$http({
url: '/home/my-api',
method: "GET",
headers: {
'Content-type': 'application/json'
},
data: JSON.stringify(request)
}).success(function(data, status, headers, config) {
}).error(function(data, status, headers, config) {
return null;
});
If you are worried about syntax, take a look at this simple example and modify it to your need.
In JS, your http.get call should contain the URL and its parameters if any,
$http.get('getUserInfo',
{
params : {
'userEmail' : 'userEmail'
}
}).then(function(response) {
console.log(response);
});
If you are passing a parameter to the API call, ensure your Java controller or the service has the parameter defined to receive the same. Ideally the parameters should match between the call and the provider
For example, for the above API call, the spring controller should like below,
#RequestMapping(value = "/getUserInfo", method = RequestMethod.GET)
public #ResponseBody User getUserInfo(
#RequestParam("userEmail") String userEmail) {
// Do Something
}

Calling a C# method from JavaScript

I want to to call a method GetAccount from my controller AccountController.cs, in my JavaScript factory LoginFactory.js. Something like this:
AccountController.cs:
public Account GetAccount(string userName)
{ ... }
LoginFactory.js:
if(x>y) {
var account = <%AccountController.GetAccount(someParam);%>
}
I've tried using [WebMethod] and Ajax, but I can't get it to work: I get a 404 response.
Assuming your GetAccount method can be reached at /Account/GetAccount when your application runs, you could use the following:
$.ajax({
type: 'GET',
url: '/Account/GetAccount',
data: { 'username' : 'a-username' },
dataType: 'json',
success: function(jsonData) {
alert(jsonData);
},
error: function() {
alert('error');
}
});
Note - this is dependant on jQuery.
This causes the browser to make a request to /Account/GetAccount as if you had done so by entering the URL in the URL bar, but of course, captures the returned json for use in your client side (javascript) script.
If this returns a 404, it would be worth checking your routing.

Crossdomain Ajax call to Service isn't working

I'm using ASP MVC and I'm trying to call a service that's on another one of my MVC websites.
I'm trying to use the following Ajax call.
function SomeFunction(decision) {
if (decision == false)
decision = "no";
else
decision = "yes";
var input = {
LogEventType:"PageView",
CurrentPage: "invitation/?decision=" + decision + "&id=" + 32323,
};
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "https://somewebsite.com/api/ClickStream/LogWebEvent/",
data: JSON.stringify(input),
crossDomain: true,
dataType: 'jsonp',
headers: {
'Access-Control-Allow-Origin': '*'
},
success: function (data) {
alert("We're awesome")
},
error: function () { console.log("Call to SomeFunction failed.") }
});
}
I don't get any visible errors and I also put breakpoints on the service and inside of the success/error function of the ajax call but it never reaches any of them.
Anyone see where I messed up?
EDIT:
Here is the Web Apis function I'm trying to access
[ActionName("LogWebEvent")]
[HttpPost]
public void LogWebEvent(ClickStreamEventDto data)
{
try
{
_clickstreamLogger.LogWebEvent(data);
}
catch (Exception ex)
{
}
}
Where ClickStreamEventDto is
public class ClickStreamEventDto: Analytics.IAnalyticEventDto
{
public string LogEventType { get; set; }
public string CurrentPage { get; set; }
}
When hitting cross domain sites, with either CORS or JSONP, make sure they are both HTTP or both HTTPS.
Make sure that when HTTPS is involved, that both site's certificates have been accepted. You may need to hit the HTTPS site in another window, and accept the certificate if there is no trust relationship to the issuer.

MVC 4 APIController not receiving POST data

Sure this had been dealt with many times... but.. just cant see what im doing wrong!
This is a simple JS script that Posts data back to ApiController.
function WebCall(url,parameterObject, callBackFunction) {
this.callbackfunction = callBackFunction;
this.parameterObject = parameterObject;
this.url = url;
self = this;
this.GetData = function () {
//self = this;
$.ajax({
//dataType: "json",
type: "POST",
url: self.url,
data: JSON.stringify(self.parameterObject),
contentType: "application/json;charset=utf-8",
success: function (data) {
self.callbackfunction.call(this, data);
},//self.GotData,
error: function (xhRequest, ErrorText, thrownError)
{
alert("error : " + ErrorText)
},
complete: function () {},
})
}
}
The data being sent (parameterObject) is simply
var postData = {
clientId: id
}
The c# code in the controller is :
public class ClientPostObject
{
public string clientId;
}
public class ClientDetailController : ApiController
{
[HttpPost]
public ClientDetailWidgetData GetClient(ClientPostObject clientObject)
{
return new ClientModel().GetClientDetail(clientObject.clientId);
}
}
In Google chrome developer tools, the XHR is showinf 'form Data' as clientId:A0001 - so that looks ok?
No matter what I try (and I'be been through many suggestions on the web), the post data is not there.
Sure its something simple.... Thanks in advance.
Unless you're planning on using a full-on form to submit to this method at some other point, it doesn't really make sense to ask the model binder to attempt to bind to a complex type when you're just using one property. Change your method signature to:
[HttpPost]
public ClientDetailWidgetData GetClient(int clientId) // or whatever type clientId represents
{
return new ClientModel().GetClientDetail(clientId);
}
I'd also recommend adding Glimpse at some point (http://getglimpse.com/) so that you can see how the model binding and/or routing of your app works.
Try to ditch contentType and don't stringify data:
$.ajax({
type: "POST",
url: self.url,
data: self.parameterObject,
success: function (data) {...},
...
});

Categories

Resources