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.
Related
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
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
I'm currently developing spring mvc application and I need to post JSON array.
When I access request.getParameter("paramValue") to fetch the param attibute, but it returning a null value,
Here is my front-end code:
$.ajax(url, {
async: true,
type: 'post',
contentType: 'application/json',
data: JSON.stringify({
"test":"test value"
})
}).done(function (response) {
console.log(data);
}).fail(function (xhr) {
console.log("request failed");
console.log(xhr);
});
Here is my server-side code:
#RequestMapping(value = "/Products", method = RequestMethod.POST)
public void saveProducts(HttpServletRequest req, HttpServletResponse res) throws Exception {
System.out.println(req.getContentType());
System.out.println(req.getContentLength());
System.out.println(req.getContextPath());
System.out.println(req.getParameterValues("test"));
System.out.println(req.getMethod());
StringBuilder buffer = new StringBuilder();
BufferedReader reader = req.getReader();
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String data = buffer.toString();
System.out.println(data);
System.out.println(req.getParameter("test"));
}
The output is:
application/json
22
null
POST
{"test" : "Test DAta"}
null
I can't figure out whats going on, please help me.
remove this line in you ajax function
contentType: 'application/json',
and replace this line
data: JSON.stringify({
"test":"test value"
})
with
data: {
"test":"test value"
}
and also you can use
req.getParameter("test")
instead
req.getParameterValues("test")
You can by using this :
var data ={id: 1, name :'test'}
$.ajax(url, {
async: true,
type: 'post',
contentType: 'application/json',
data: data
}).done(function (response) {
console.log(data);
}).fail(function (xhr) {
console.log("request failed");
console.log(xhr);
});
and in server side
create a pojo :
public class Product{
private long id;
private String name;
// getters and setters
add library jackson .
add this method in your controller:
#RequestMapping(value = "/Products", method = RequestMethod.POST)
public RepsoneEntity<? >saveProducts(#requestBody Product pr){
LOG.debug(pr.toString());
return new reRepsoneEntity<Product>(pr,HttpStatus.ACCEPTED);
}
i finally fixed it several annotation and changing the the return type of server side method,
#RequestMapping(value = "/Products", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
public ResponseEntity<?> saveProducts(#RequestParam(value = "data") String brand) {
return ResponseEntity.ok(brand);
}</code>
front end
$.ajax(url, {
async: true,
type: "POST",
data: {"data" : JSON.stringify({"Brand" : "Test Brand"})}
}).done(function (response) {
console.log(response);
}).fail(function (xhr) {
console.log("request failed");
console.log(xhr);
});
and i used org.json to access json objects parsed as text, gson to deal with POJOs
and now it works :)
Every request ajax getting an error.
Ajax function:
function doAjax() {
var inputText = $("#info").val();
$.ajax({
type: 'POST',
url: 'ajax',
// data: ({text: inputText}),
dataType: 'json',
data: 'text='+inputText,
success: function (response) {
$("#result_info").text(response);
}
error: function (e) {
alert('error' + e.responseText);
}
});
}
Java Controller
#RequestMapping(value = {"/ajax"}, method = RequestMethod.POST)
public #ResponseBody String showText(#RequestParam String text) {
System.out.println(text);
String returnText = "empty";
if (!text.isEmpty()) {
returnText = " response: " + text;
}
return returnText;
}
Besides this question could you tell what is the difference between in ajax query
data: ({text: inputText}),
data: 'text='+inputText,
In this particular case it's better to change dataType to html instead of json. I solved it.
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)