i am attempting to return a response result from spring in java to a html page but failing to receive the response. Basically my searchRoom method attempts to search a room for availability and if it's available returns true or else false. My response message is passed to the html file and upon the response should inform the user if available or not. But i am not able to receive the response please could someone tell me what i did wrong. And a side note i tried to do a console log but failed to print either true or false.
Below is my Java Code:
#RequestMapping(value = "/guest/search", method = RequestMethod.POST)
public String SearchRoom(#RequestBody Occupancy occupancy, ModelMap model){
boolean result = occupancyservice.searchAvlRoom(occupancy);
System.out.print(result);
model.addAttribute("result", result);
return "guest";
}
Below is my query function that post the data and receives response:
$("#checkAvailabilityForm").submit(function(e){
e.preventDefault();
var formData={
"checkInDate": $("#checkInDate").val(),
"checkOutDate": $("#checkOutDate").val(),
"roomsWanted":$("#roomsWanted").val(),
"room":{
"roomType": $("input[name=roomType]:checked").val(),
"roomProperties":$("input[name=roomProperties]:checked").val()
}
};
$.ajax({
type: 'post',
url: 'guest/search',
dataType: 'json',
data: JSON.stringify(formData),
contentType: 'application/json',
success: function(dataRecieved){
var dataRecieved= $.trim(dataRecieved);
console.log(dataRecieved);
/*if(dataRecieved === ''){
}else{
}*/
}
});
Actually figured it out. I forgot to use #ResponseBody annotation and the code below solved my problem:
#RequestMapping(value = "/guest/search", method = RequestMethod.POST)
#ResponseBody
public boolean SearchRoom(#RequestBody Occupancy occupancy){
boolean result = occupancyservice.searchAvlRoom(occupancy);
return result;
}
Related
I want to use following ajax method to call a java function (I use Spring Boot and Hibernate) and read the return value afterwards. The function '/myFunction' is correctly called and the return value is a string and is correctly logged in the java function. But I don't get it, how I can use the return message from the java-method in the success-part afterwards. (notifyUser is a little function(title, message) that shows a notification to an user, this function works correctly) By now, notifyUser just post Error [object Object]
$.ajax({
type : 'POST',
contentType : 'application/json',
url : '/myFunction',
data : JSON.stringify({
fooM,
fooO,
fooS
}),
dataType : 'json',
cache : false,
timeout : 600000,
success : function(data) {
notifyUser('Info', data);
},
error : function(e) {
notifyUser('Error', e);
}
});
#RestController
#Secured({ "ROLE_USER", "ROLE_ADMIN" })
public class MyController {
#RequestMapping(value = "/myFunction", method = RequestMethod.POST)
public String myFunction(#RequestBody MyRequestClass request ) {
String return_string = "Check if return value works " + request.getFooM() + request.getFooO() +request.getFooS();
log.debug(return_string)
//Up to this step, everything works
return return_string;
}
}
What do I have to change, that I'm able to get the return value of the called function '/myFunction' in the success part and send the string to notifyUser?
Thank you for your answers.
Phil
i tried accessing my controller through ajax to get DB results but it wont work. The ajax is inside a submit button and executes well without the ajax. The code is supposed to execute a query and check if the input exists.
Here's my ajax
var jsonData = {
"appname": appname,
"txtype": txtype,
"ipaddress": ipaddress
};
$.ajax({
type: 'POST',
url: "checkaccesspermission.html",
data: jsonData,
success: function(data) {
if(data == "exists"){
alert('Permission Already Exists!');
return false;
}else{
alert('Add Permission test Succesful!');
return true;
}
},
async: false
});
here's my controller
#RequestMapping(value="/checkaccesspermission", method=RequestMethod.GET)
public String checkaccesspermission(#ModelAttribute("loginForm") IpAccessManagementModel loginForm, Model model,
#RequestParam("ipaddress") String ipaddress,
#RequestParam("txtypeHidden") String txtype,
#RequestParam("appIDHidden") String appID) throws IOException{
System.out.println("CHECKACCESSPERMISSIONs");
IpAccessManagementModel sub = new IpAccessManagementModel();
//System.out.println("<script language='JavaScript'>alert('Hello');</script>");
sub.setAppName(appID);
sub.setTxtType(txtype);
sub.setIpAddress(ipaddress);
System.out.println(ipaddress);
ipAccessMGTDAO.addPermission(sub);
String resultCheckExist = ipAccessMGTDAO.checkAccessPermission(sub);
return resultCheckExist;
}
Remove the .html extension and Change your method annotation in the controller to method=RequestMethod.POST
also remove
#RequestParam("ipaddress") String ipaddress,
#RequestParam("txtypeHidden") String txtype,
#RequestParam("appIDHidden") String appID
because its a Post request
Here I try to make a simple post request to my controller with an url as post body. After ajax call completes, I don't receive the response from the controller. Why ?
This is my controller:
#RestController
public class Controller {
#RequestMapping(value = "/authenticate", method = RequestMethod.POST, consumes = {"application/json"})
public ResponseEntity<String> authenticate(#RequestBody String url) {
System.out.println(url);
return new ResponseEntity<>("TOKEN", HttpStatus.OK);
}
}
And the ajax call:
var url = 'https://slack.com/api/oauth.access' +
'&client_id=' + client_id + '&client_secret=' + client_secret + '&code=' + code + '&redirect_uri=' + redirect_uri;
$.ajax({
url: "/authenticate",
type: 'POST',
data: JSON.stringify(url),
contentType: 'application/json',
dataType: 'json'
}).done(function (data) {
console.log(data);
})
Nothing is printed in the console. Can you tell me what the problem is please ?
It turns out that the string that I return from the controller cannot be parsed to json because it doesn't have a valid format
I changed the line
return new ResponseEntity<>("TOKEN", HttpStatus.OK);
to
return new ResponseEntity<>("\"TOKEN\"", HttpStatus.OK);
And it works fine.
Return JSON for ResponseEntity<String>
#Gustavo
Hi, have you tried JSON view?
JSON always returns a key value; by which we can access elements.
Mostly the key value is suffix with 'Result' along with Funcation name.
If your looking at JSON.stringfy("..") is used to just check if data received is correct, after hat you need to paese J
var text = JSON.parse(response.data.GetAllDataResult);
I am trying to call a spring controller using ajax, but can not able to go to the controller. I am getting Error 405 Request method 'POST' not supported error. I am keeping my code here please give suggestion to come over it
this is my ajax code calling controller from jsp page, here i am getting the anchor attribute value.
basic.jsp
function organizationData(anchor) {
var value = anchor.getAttribute('value');
$.ajax({
url : "manageOrganization",
method : "GET",
dataType: "json",
contentType: 'application/json',
data: {organizationId : value },
success : function(response) {
alert(response);
},
error : function(e) {
alert('Error: ' + e);
}
});
}
controller
#RequestMapping(value="/manageOrganization", method = RequestMethod.GET)
public String organizationData(#RequestParam String organizationId) {
return organizationId+" associated";
}
here i should get the string to the jsp as a ajax response, but i am getting the error message. Any body can help me.
Regards Sree
For json response you need to add #ResponseBody annotation to your controller method.
You need to use type:"GET" not method:"GET" try it like,
$.ajax({
url : "manageOrganization",
type : "GET", // its type not method
dataType: "json",
.....
Read jQuery.ajax()
Also check that you are returning a json or not.
Your controller is returning String which may be resolved into some other jsp file IF you have configured viewResolver in spring configuration file. Try adding #ResponseBody like this:
#RequestMapping(value="/manageOrganization", method = RequestMethod.GET)
public #ResponseBody
String organizationData(#RequestParam String organizationId) {
return organizationId+" associated";
}
I have the page about.ftl which is invoked when I type localhost:8080/ui/about
and I have put the following block of code inside. Through SendToServlet() function I am trying to send the user info to my controller which is the OAuthController.java
function SendToServlet(){
$.ajax({
url: "localhost:8080/ui/about",
type: "POST",
data: JSON.stringify({ user:jsonObj}),
contentType: 'application/json',
success: function(result) {
alert(done);
},
error: function(xhRequest, ErrorText, thrownError) {
alert(JSON.stringify(jsonObj));
}
});
}
</script>
My Spring MVC Controller class code has the following implementation - all that it does is that it accepts the user's information and then sets up current user:
#Controller
#RequestMapping("/about")
public class OAuthController {
#RequestMapping(method = RequestMethod.POST)
#ResponseBody
public String post( #RequestBody String items, HttpServletRequest request, HttpServletResponse response)
{
String jsonResp = items;//sb.toString();
ArrayList<String> usercredentials = new ArrayList<String>();
usercredentials = parseJson(jsonResp);
UserMethods usermethods = new UserMethods();
usermethods.setCurrentUser (usercredentials);
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
return "{\"success\":\"\"}";
}
public ArrayList<String> parseJson(String json){
}
}
My problem is that the controller is never invoked and actually I never see a Post request to be sent anywhere through Firebug. I've spent several days on it, but still no luck. Do you have any suggestions?
You need to bind value with your function. Your url localhost:8080/ui/about/post is just used to locate the controller but it will not execute any function because you didn't make a call to any function.
To call the function, you have to do like this :
#RequestMapping(method = RequestMethod.POST, value ="/anyValue")
public String anyFunctionName(anyParam){...}
Above function will bind to url localhost:8080/ui/about/anyValue.
Don't you need to call it like this?
url: "localhost:8080/ui/about/post",
but first do this:
#RequestMapping(method = RequestMethod.POST, value = "/post")
How about try to add .html?Application won't add it automatically.