my ajax wont execute my controller - java

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

Related

My AJAX wont run the SUCCESS Function but executes my controller, JAVA

I'm trying to execute my controller and get the return string to be used for my alert message, but my success function won't work. It executes the controller but does not execute the success function. The error executes but does not display any message.
BELOW IS THE AJAX
var jsonData = {
"appIDHidden": appname,
"txtypeHidden": txtype,
"ipaddress": ipaddress
};
$.ajax({
type: 'POST',
url: "checkaccesspermission",
data: jsonData,
dataType: 'json',
success: function(data) {
if(data != "exists"){
alert('Permission Already Exists!');
return false;
}else{
alert('Add Permission test Succesful!');
return true;
}
alert('test123');
},
error: function(jqXHR, textStatus, thrownError)
{
alert(thrownError+jsonData[1]);
},
async: false
});
BELOW IS THE CONTROLLER
#RequestMapping(value="/checkaccesspermission", method=RequestMethod.POST)
public String checkaccesspermission(#ModelAttribute("loginForm") IpAccessManagementModel loginForm, Model model,
HttpSession session, BindingResult result,HttpServletRequest request,
#RequestParam("ipaddress") String ipaddress,
#RequestParam("txtypeHidden") String txtype,
#RequestParam("appIDHidden") String appID) throws IOException{
System.out.println("CHECKACCESSPERMISSIONs");
IpAccessManagementModel sub = new IpAccessManagementModel();
sub.setAppName(appID);
sub.setTxtType(txtype);
sub.setIpAddress(ipaddress);
System.out.println(ipaddress);
ipAccessMGTDAO.addPermission(sub);
String resultCheckExist = ipAccessMGTDAO.checkAccessPermission(sub);
System.out.println("checkResult:|"+resultCheckExist+"|");
return resultCheckExist;
}
Nevermind, i got it to work by adding #public ResponseBody on my Controller :#RequestMapping(value="/checkaccesspermission", method=RequestMethod.POST)
public #ResponseBody
String checkaccesspermission

Pass model and a string using ajax to Spring MVC

Hi I need to pass the full model and one string from html to Spring controller using AJAX. I use the below code snippet but it doesn't work.
var str = $("#resourceManagement").serialize();
var agreementId = ${agreementId};
var tempCnltName=$modal.find("input[data-type='cnltName']").val();
$.ajax({
type:"POST",
data: {str, tempCnltName},
url: "${AGREEMENT_BASE_URL}/checkDuplicateConsultantOnline",
async: false,
dataType: "json",
success: function (data, status, xhr) {
message = data.errorMsg;
},
error: function () {
}
});
The problem is that if I pass model alone (str) or string alone (tempCnltName) I can get it in controller but I cannot get both together.
My controller is as below:
#RequestMapping(value = "/app/agreement/checkDuplicateConsultantOnline", method = RequestMethod.POST)
public #ResponseBody AjaxResponse checkDuplicateConsultantOnline(
#ModelAttribute("consultantBidModel") ConsultantBidModel model,
#RequestParam(value = "tempCnltName", required = false) String cnltName,
HttpServletRequest request,
HttpSession session) throws Exception {
final Set<String> allCnltNames = new HashSet<>();
String errMessage = "";
if (model.getLeadingCnltName() != null) {
allCnltNames.add(model.getLeadingCnltName().toLowerCase());
}
if (model.getJointVentureConsultants() != null) {
for (ConsultantBidListItem entry : model.getJointVentureConsultants()) {
if (!allCnltNames.add(entry.getCnltName().toLowerCase())) {
errMessage = "Each consultant can only appear once.";
}
}
}
if (model.getSubConsultants() != null) {
for (ConsultantBidListItem entry : model.getSubConsultants()) {
if (!allCnltNames.add(entry.getCnltName().toLowerCase())) {
errMessage = "Each consultant can only appear once.";
}
}
}
AjaxResponse response = new AjaxResponse();
if (errMessage != null) {
response.setSuccess(true);
response.setResponseObject(errMessage);
response.setErrorMsg(errMessage);
}
return response;
}
On the server side, you're already prepared to receive both the model (with #ModelAttribute) and an additional URL parameter (with #RequestParam)
On the client, append the URL parameter to the URL. Assuming that str is your model and tempCnltName is your string to submit to the server:
$.ajax({
type:"POST",
data: str,
url: "${AGREEMENT_BASE_URL}/checkDuplicateConsultantOnline?tempCnltName=" + tempCnltName,
...
try
var strVal = $("#resourceManagement").serialize();
var agreementId = ${agreementId};
var tempCnltNameVal=$modal.find("input[data-type='cnltName']").val();
$.ajax({
type:"POST",
data: {str: strVal, tempCnltName: tempCnltNameVal},
url: "${AGREEMENT_BASE_URL}/checkDuplicateConsultantOnline",
async: false,
dataType: "json",
success: function (data, status, xhr) {
message = data.errorMsg;
},
error: function () {
}
});
Probably the malformed json is causing trouble
Another way of doing the above, add the string to model:
var strVal = "consulName=" + tempCnltName + "&";strVal = strVal + $("#resourceManagement").serialize();
The model can then have a new parameter consulName and we can get the value in Controller.

What is the correct way to send a string using AJAX with Spring and Thymeleaf? Status : 400

I am getting error ""Required UsernameSearch parameter 'username' is not present" when sending data using ajax with Spring and Thymeleaf. My script is as shown below
<script>
$(document).ready(function() {
$("#opusername").keyup(function() {
var username = $('#opusername').text();
$.ajax({
type : "POST",
contentType : "application/json",
url : "/create/check-username-availability",
data : {"username" : username},
dataType : 'json',
timeout : 100000,
success : function(data) {
console.log("SUCCESS: ", data);
},
error : function(e) {
console.log("ERROR: ", e);
},
done : function(e) {
console.log("DONE");
}
});
});
});
My controller has this method which should receive the string and return a value to indicate whether the username is available or not.
#RequestMapping(value = "/create/check-username-availability", method = RequestMethod.POST)
#ResponseBody
public String checkUsernameAvailability(#RequestParam("username") UsernameSearch username) {
logger.info("Checking username availability for username = " + username.getUsername());
return "true";
}
This is the object I create which contains the username String. I have done this after following tutorials and answers here but nothing seems to work.
public class UsernameSearch {
String username;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
This is the error when debugging
error:"Bad Request"
exception:"org.springframework.web.bind.MissingServletRequestParameterException"
message:"Required UsernameSearch parameter 'username' is not present"
path:"/create/check-username-availability"
status:400
timestamp:1489942516434
I also wanted to ask how to consume the result from the spring method. Is it possible to get a boolean value?
Change #RequestParam to #RequestBody. Request param != body of the request.
The 400 HTTP error means that the the request is malformed. In your case, the controller expects that the url will have a "username" parameter. Therefore you can either change the ajax call, to send the username as the request parameter, i.e. by attaching "?username=fooBar" to the url you're perfoming POST request and change the controller method signature to accept #RequestParam("username") String username, or change the annotation on the controller parameter to #RequestBody, which tells the controller that the data will be sent as an object in the body of the request.
function ajax:
var data = {
username: $('#opusername').text()
};
$.ajax({
type: "POST",
contentType: 'application/json; charset=utf-8',
dataType: 'json',
url: "/create/check-username-availability",
data: JSON.stringify(data), // Note it is important
success: function (result) {
// do whatever you want with data
}
});
and in your java method
#RequestMapping(value = "/create/check-username-availability", method = RequestMethod.POST)
#ResponseBody
public String checkUsernameAvailability(#RequestBody UsernameSearch username) {
logger.info("Checking username availability for username = " + username.getUsername());
return "true";
}
Don't send your data as string!
Do the following:
data : {"username" : username},
I think you are getting caught up with the various levels all labeled as username. As your server is written now, it is expecting a parameter which is identified as username to be of type UsernameSearch which is an object with a single property of username. To be explicit, you are expecting the sent body (which is an object) to have a property of username where the value is an object which also has a property called username. So the server is expecting
{
'username': {
'username': 'search value'
}
}
What you are sending is an object with a property of 'username' but a value of string:
{
'username': 'search value'
}
The answer is to be consistent. If you think your search criteria will become more than the one field, then update your client, if not, then change the server to accept a string rather than an object.
Update:
Also, you have #RequestParam but you should use #RequestBody.

Unable to receive response from rest api in spring on front end

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;
}

Call java method with JQuery

I developed a message system and in the inbox I want to delete multiple messages selecting it with some checks and calling the delete method but I don't know if I can do it witout a form. Some people tells me that I can do with JQuery but I don't know how to do.
MessagesController.java
#RequestMapping(value = "/mensajes/delete/{menssageId}")
public String menssagesDelete(final ModelMap model, #PathVariable("menssageId") final Integer mensajeId,
final HttpServletRequest request, final RedirectAttributes redirectAttrs) {
final User user = (User) request.getSession().getAttribute(Constantes.SESSION_USER_KEY);
final Mensajes mensaje = this.mensajesService.loadMensaje(mensajeId);
this.mensajesService.deleteMensaje(mensaje);
return "redirect:/menssages/home";
}
EDIT:
Now I have this:
MessagesController.java
#ResponseBody
#RequestMapping(value = "/mensajes/deleteMensajes.json", method = RequestMethod.GET, headers = "Accept=application/json")
public void deleteMensajes(final String[] arrayMensajes) {
}
And this is de js code:
function eliminarMensajes(){
var arrayMensajesSeleccionados = jQuery('[name="msgIdRecibido"]:checked').map(function () {
return this.value;
}).get();
//Llamada ajax
$.ajax({
type: "GET",
url: "deleteMensajes.json",
data:{'arrayMensajes': arrayMensajesSeleccionados},
async: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
alert("hola");
}
});
When enter the controller method the arrayMensajes is null What Im doing wrong?
It works when add this to controller
public void deleteMensajes(#RequestParam(value="arrayMensajes[]", required=false) final String[] arrayMensajes)

Categories

Resources