Javascript AJAX call to SpringBoot controller and getting response in JSON - javascript

I am trying to hit my SpringBoot controller with a JSON and for that I am using AJAX. I want my controlelr to receive the AJAX call, extract the JSON, works with the values and return a JSON response back to the script which I will then utilize in some way.
I am not able to figure out how to code my controller so as to handle the AJAX and also if the request should be POST or GET ?
Here is my script code:
<script>
database.on('child_added', function (snapshot) {
var data = {};
data["FirstName"] = snapshot.val().FirstName;
data["LastName"] = snapshot.val().LastName;
data["Number"] = snapshot.val().Number;
$.ajax({
type: "GET",
contentType: "application/json",
url:"my-localhost/application/print",
data: JSON.stringify(data),
dataType: 'json',
cache: false,
success: function(){
console.log("Successfully sent payload")
},
error: function(e){
console.log("Error": , e)
}
});
</script>
Here is my controller for now. I dont know how and what to change in it and how to send the response back to the script:
#RestController
#RequestMapping("/application")
public class AppController
{
#GetMapping("/print")
public void print()
{
System.out.println("Hello World");
}
}

I am not able to figure out how to code my controller so as to handle the AJAX and also if the request should be POST or GET ?
Your service method is annotated as #GetMapping("/print") so it should be GET request. I suggest reading a bit more on various HTTP methods and then decide which one serves you best.
Here is my controller for now. I dont know how and what to change in it and how to send the response back to the script.
You should be returning the object which encapsulates the data you want to send back to the consumer.

Simply it has three steps
Create DTO object (property name must be according to your JSON object names)
User #RequestBody in your method
Use #ReponseBody and simply return the object.
Example:
Consider it you want to send some user information, do some business and return that user to the javascript (UI).
Create DTO class for user
#JsonInclude(JsonInclude.Include.NON_NULL)
#JsonIgnoreProperties(ignoreUnknown = true)
public class UserDto {
private Long id;
private String name;
private String family;
private String password;
private String username;
private String nationalId;
private String email;
//Getters and Setters
}
Put #RequestBody and User class as the input of the controller
method.
Simply return user object.
#RestController
#RequestMapping("/application")
public class AppController {
//Changed to #PostMapping
#PostMapping("/print")
public User print(#RequestBody User user) {
//Do whatever you want to user
System.out.println("Hello World" + user.getUsername());
return user;
}
}
Some notes
#RequestBody, works as a converter to convert sent JSON to a java class (Convert user JSON to User.class)
#ResponseBody, is inverse of #RequestBody, it converts java classes to JSON (Convert User.class into user JSON)
As you're sending data to the server it's good for you to use POST
instead of GET. GET OF POST
DTO object property names (family, id,...) must be the same as your
JSON property names. Otherwise, you must use #JsonProperty.
Further information about JsonProperty
When you're using #RestController you don't need to use
#ResponseBody
because it's in body of #RestContoller

Related

JQuery ajax- current URL doesn't work

I've looked at thousands of articles about my problem, but i didn't found a solution.
Here we go.
When I'm using ajax with url specified as the url of view when i want to use a script it doesn't work. I'm using POST type and receiving data in spring controller. When I change url to something else and do the same in requestmapping value, everything works fine. What possibly causing this problem ? AJAX:
$.ajax({
type : "POST",
url : "/login2",
data :
{x: x}
,
success : function() {
alert('fine');
},
error: function(xhr, status, error) {
alert(xhr.status+status+error);
}
});
SPRING:
#Controller
#RequestMapping
public class LoginController {
#RequestMapping(value = "/login",method = RequestMethod.GET)
public String login() {
return "login";
}
#RequestMapping(value = "/login2",method =RequestMethod.POST)
public #ResponseBody void login2(#RequestParam(value="x[]") String x[]){
System.out.println(x[1]);
}
}
Code above works fine but
When url is "/login" for whole class and methods are specified the same it doesn't work ..
Can You help me please ?
Your parameter for login2 is array of string. Whereas you are sending object from ajax.
try reading the values from Request body instead of request param.
login2(#RequestBody String x[])
Maybe problem is that this is my page declared as login apge in Spring Security ?

Ajax data not reaching backend C# code

Below is the code which i m trying to send. As you can see, ajax call is made at UI and data 'sub' is passed through. this 'sub' has an array of objects in it. So data is present when it is passed.
UI SIDE
$scope.save = function () {
var sanit = $scope.gridOptions.rowData;
var sub = JSON.stringify(sanit);
$.ajax({
type: 'POST',
url: '/api/Pr/PM',
data: sub, //this has data in it
contentType: "application/json"
}).success(function (response) {
window.alert("Database updated successfully.");
})
};
However, when i debug the code at backend, the parameters is showing as null. i have commented the section showing this is null where the data is showing as null at the start of backend function.
BACKEND C# SIDE
[HttpPost]
public HttpResponseMessage PM([FromBody] string parameters) //this is null.
{
string message = string.Empty;
try
{
var model = JsonConvert.DeserializeObject<List<PODetails>>(parameters);
message = "Insert Successfull";
return Request.CreateResponse(HttpStatusCode.OK, message);
}
catch (Exception ex)
{
message = "Insert fail";
return Request.CreateErrorResponse(HttpStatusCode.NoContent, message);
}
}
Can someone please let me know why it is showing as null value at backend.
You need to ensure the data you're sending via AJAX is an object with a single parameter, which should be named the exact same as the parameter your backend is expecting.
In this case:
$.ajax({
type: 'POST',
url: '/api',
data: JSON.stringify({ parameters: sub }),
contentType: "application/json"
}).success(function (response) {
...
})
Next, if the variable "sub" is an array of objects then you must create a class model server side to match the structure of the data being sent. Then, your API's interface should be expecting a list of that newly created class.
For example:
[HttpPost]
public HttpResponseMessage PM(List<YourClassModel> parameters)
{
...
}
Your API should now be able to receive and read the data being sent via the AJAX call above.
Take a look at this: Post a json object to mvc controller with jquery and ajax
You are sending a list of objects but trying to recieve it as string. You should change your function parameter from (String parameters) to (List parameters) and change your ajax request according to the link above. That will probably solve your problem.
(ps: i couldn't try it myself that's why i said probably :) )

How can I get a Spring #RestController to accept parameters in JSON format rather than www-form-urlencoded?

Using Spring 4.1.7 on JDK 1.8, I have an #RestController class that looks like this:
#RestController
public class ServiceAController {
public static final Logger LOG = Logger.getLogger(ServiceAController.class);
#RequestMapping(value="/rest/servicea", method=RequestMethod.POST)
public ServiceAResponse serviceA(#RequestParam(value="parmA", defaultValue="defaultParmA") String parmA,
#RequestParam(value="parmB", defaultValue="defaultParmB") String parmB,
#RequestParam(value="parmC", defaultValue="defaulParmC") String parmC) {
LOG.info("Inside Service A handler: " + parmA + " B: "+ parmB + " C: "+ parmC);
}
When I send a POST to /rest/servicea from a javascript like this, everything works, and I see the values "a", "b", and "c" printed in my log:
var data = {
"parmA": "a",
"parmB": "b",
"parmC": "c"
}
$.ajax({
type: "POST",
url: "./rest/servicea",
contentType: "application/x-www-form-urlencoded",
data: data,
dataType: "json",
success: submitAuthSuccess,
error: submitAuthFailure
})
However, when I try to change the call from the javascript to this (to change the protocol to REST rather than www-urlencode), I get the default values (defaultParmA, defaultParmB, defaultParmC) in my log:
var data = {
"parmA": "a",
"parmB": "b",
"parmC": "c"
}
$.ajax({
type: "POST",
url: "./rest/servicea",
contentType: "application/json",
data: JSON.stringify(data),
dataType: "json",
success: submitAuthSuccess,
error: submitAuthFailure
})
I think I'm missing something in the #RestController class to get it to parse the JSON rather than expecting www-urlencoded data.
I tried changing the #RequestMapping annotation on the serviceA method to add the consumes="application/json" attribute, but that had no effect.
What can I change to make this work, using JSON rather than urlencoded data in the POST body?
The #RequestParam javadoc states
Annotation which indicates that a method parameter should be bound to
a web request parameter.
This is retrieved through the various ServletRequest methods for request parameters. For example, ServletRequest#getParameterMap() which states
Request parameters are extra information sent with the request. For
HTTP servlets, parameters are contained in the query string or posted
form data.
In your second snippet, you aren't sending either. You're sending JSON in the request body.
Spring has a mechanism (it has many, and custom ones) for deserializing that into the data you expect. The standard solution is #RequestBody, assuming you have an appropriately registered HttpMessageConverter that can handle the JSON. Spring automatically registers MappingJackson2HttpMessageConverter if you have Jackson 2 on the classpath, which can correctly deserialize JSON into Java POJO types.
The documentation gives a number of examples and explains how you would use it. With JSON, you could define a POJO type with fields that correspond to the ones you send
class RequestPojo {
private String paramA;
private String paramB;
private String paramC;
// and corresponding getters and setters
}
and add a #RequestBody annotated parameter of this type to your handler method
public ServiceAResponse serviceA(#RequestBody RequestPojo pojo) {
pojo.getParamB(); // do something
return ...;
}
Jackson lets you define, through annotations or through configuration of the ObjectMapper, how to deal with absent values.
#RestController is not involved here. As its javadoc states,
Types that carry this annotation are treated as controllers where
#RequestMapping methods assume #ResponseBody semantics by default.
It looks to me like you are passing a single JSON object at this point, rather than a set of parameters, hence Spring cannot match what you're sending to any of the parameters you've provided.
Try
#RequestBody List<ListUnit> listOfUnits
instead of #RequestParam

Web Service method name is not valid

I get the following error "Web Service method name is not valid" when i try to call webmethod from javascript
System.InvalidOperationException: SaveBOAT Web Service method name is not valid.
at System.Web.Services.Protocols.HttpServerProtocol.Initialize()
at System.Web.Services.Protocols.ServerProtocol.SetContext(Type type, HttpContext context, HttpRequest request, HttpResponse response)
at System.Web.Services.Protocols.ServerProtocolFactory.Create(Type type, HttpContext context, HttpRequest request, HttpResponse response, Boolean& abortProcessing)
HTML Code :
<asp:LinkButton runat="server" ID="lnkAddBoat" OnClientClick="javascript:AddMyBoat(); return false;"></asp:LinkButton>
JS Code :
function AddMyBoat() {
var b = document.getElementById('HdnControlId').value;
jQuery.ajax({
type: "GET",
url: "/AllService.asmx/SaveBOAT",
data: { Pid: b },
contentType: "application/text",
dataType: "text",
success: function(dd) {
alert('Success' + dd);
},
error: function(dd) {
alert('There is error' + dd.responseText);
}
});
}
C# Code (Web method in AllService.asmx file)
[WebMethod]
public static string SaveBOAT(int Pid)
{
// My Code is here
//I can put anythng here
SessionManager.MemberID = Pid;
return "";
}
I tried all solutions found on Stack Overflow and ASP.NET site.but none of them worked for me.
It was a silly mistake.
remove Static keyword from method declaration.
[WebMethod]
public string SaveBOAT(string Pid)
{
SessionManager.MemberID = Pid;
return "";
}
In my case I had copied another asmx file, but not changed the class property to the name of the new class in the asmx file itself (Right click on asmx file -> View Markup)
In my case the error was that the Web Service method was declared "private" instead of "public"
Try using this, I think datatype should be JSON
jQuery.ajax({
type: "POST", // or GET
url: "/AllService.asmx/SaveBOAT",
data: { Pid: b },
contentType: "application/json; charset=utf-8",
dataType: "json"
success: function(dd) {
alert('Success' + dd);
},
error: function(dd) {
alert('There is error' + dd.responseText);
}
});
And in C# Code change Pid to string
[WebMethod]
public static string SaveBOAT(string Pid)
{
SessionManager.MemberID = Pid;
return "";
}
I too faced the similar issue. The solution includes checking everything related to ensuring all name, parameters are passed correctly as many have responded. Make sure that the web method name that we are calling in UI page is spelled correctly, the data, data types are correct and etc. In my case, I misspelled the web method name in my ajax call. It works fine once I found and corrected the name correctly.
For Ex: In .asmx class file, this is the method name "IsLeaseMentorExistWithTheSameName" but when I called from UI this is how I called:
var varURL = <%=Page.ResolveUrl("~/Main/BuildCriteria.asmx") %> + '/IsLeaseMentorExistWithSameName';
Notice that the word "The" is missing. That was a mistake and I corrected and so it worked fine.
As Sundar Rajan states, check the parameters are also correct. My instance of this error was because I had failed to pass any parameters (as a body in a POST request) and the asmx web method was expecting a named parameter, because of this the binding logic failed to match up the request to the method name, even though the name itself is actually correct.
[WebMethod]
public object MyWebMethod(object parameter)
If there is no parameter in the body of the request then you will get this error.
Did U add ServiceReference Class. Check this once. Based on your comment I can tell what to do
I had this issue because my soap method had a List<string> parameter. Couldn't figure out a way to make it work with the array parameter; so just converted the parameter to a &-delimited string (e.g. val1&val2&val3) and converted the parameter to an array in the service method.
In my case, one of the WebService receiving parameters was called aId. When I called it from javascript, I was sending the correct Id value, but the name of the sent variable was incorrectly called bId. So I just had to rename the WebService call, keep the correct value like before, and just change the variable name.

Getting JSON Object Result from $.post()

I'm attempting to call a web service via AJAX in a WebForms application.
My script looks something like this:
$.post('UpdateServer.asmx/ProcessItem',
'itemId=' + $(this).text(),
function (result) {
alert(result);
});
My web service looks something like this.
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]
public class UpdateServer : System.Web.Services.WebService
{
[WebMethod]
public string ProcessItem(int itemId)
{
return new JavaScriptSerializer().Serialize(
new { Success = true, Message = "Here I am!" });
}
}
The web method is called as expected and with the expected argument. However, the argument passed to my success function (last parameter to $.post()) is of type document and does not contain the Success and Message members that I'm expecting.
What's are the magic words so that I can get back the object I'm expecting?
EDIT
On closer inspection, I can find the data I'm looking for as follows:
result.childNodes[0].childNodes[0].data:
"{"Success":true,"Message":"Server successfully updated!"}"
The reason you're seeing that odd structure of nodes that end with JSON is because you're not calling the service the necessary way to coax JSON out of ASMX ScriptServices and then returning a JSON string anyway. So, the end result is that you're returning an XML document that contains a single value of that JSON string.
The two specific problems you're running into right now are that you're manually JSON serializing your return value and you're not calling the service with a Content-Type of application/json (.NET needs that to switch to JSON serializing the response).
Once you fixed those issues, you'd also run into an "invalid JSON primitive" error due to the data parameter being URL encoded instead of a valid JSON string.
To get it working, do this on the server-side:
[ScriptService]
public class UpdateServer : System.Web.Services.WebService
{
[WebMethod]
public object ProcessItem(int itemId)
{
return new { Success = true, Message = "Here I am!" };
}
}
You could also create a data transfer object (aka ViewModel) to return instead of using an anonymous type and object, if you want.
To successfully get raw JSON out of that, do this on the client-side:
$.ajax({
url: 'UpdateServer.asmx/ProcessItem',
type: 'post',
contentType: 'application/json',
data: '{"itemId":' + $(this).text() + '}',
success: function(result) {
// This will be { d: { Success: true, Message: "Here I am!" } }.
console.log(result);
}
});
If you have a few minutes, read through the posts in the communication section of jQuery for the ASP.NET developer. You'll find a lot of that information helpful as you continue down this path.
Note: The links that helmus left were relevant. Nothing has fundamentally changed between 2.0 and present with regards to using ASMX ScriptServices to communicate via JSON. If you're interested in the truly cutting edge approach to this problem in .NET, ASP.NET Web API is the way to go.
Add this attribute to your ProcessItem method:
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
Be more explicit in your $.post call.
$.ajax({
type:'post',
url:'UpdateServer.asmx/ProcessItem',
data: {'itemId':$(this).text()}
}).done(function (result) {
alert(result);
});

Categories