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
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
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.
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 :)
I am trying to call a controller from jquery.Here every thing works fine,but in ajax it shows error alert. What is going wrong.
$.ajax({
type: 'POST',
url:'<%=request.getContextPath()%>/billing',
data: ({caseId: caseId, noteID : noteID}),
cache: false,
success: function(data){
alert("Success");
},
error: function(xhr, textStatus, error){
alert("Error occured.");
}
});
My controller
#RequestMapping(value = "/billing", method = RequestMethod.POST)
public String Billing(#RequestParam Long caseId,
#RequestParam Long noteID, HttpServletRequest request) throws Exception {
try{
----Some data base updation---
logger.debug("success ");
return "success";
} catch (Exception e) {
logger.error(e,e);
throw e;
}}
Please help me in this.
//you have to left content type to send the server side ,please define content type..
$.ajax({
type: "POST",
url: '#Url.Action("PerTGradeMastEdit", "Master")',
data: "{'Request':'" + request + "'}",
contentType: "application/json; charset=utf-8",
success: function (response) {
if (response != null) {
var strResponse = response;
var ProgramData = strResponse.split("/");
// response = ProgramData[0];programId
$('#txtPerGrade').val(ProgramData[0]);
$('#txtDesc').val(ProgramData[1]);
}
},
failure: function (msg) {
alert(msg);
window.location.href = '#Url.Action("INDEX", "AUTHORIZE")';
}
});`enter code here`
I have a Spring MVC controller that I am calling via JQuery.ajax.
The mapping in the controller is:
#RequestMapping(value = "/remove", method = RequestMethod.POST)
#ResponseBody
public void remove(#RequestParam("value1") String value1,
#RequestParam("value2") String value2)
{
// do stuff
}
The ajax call is:
$.ajax({
url: '/appserver/model/remove',
data: { value1: value1, value2: value2 },
type: 'POST',
traditional: true,
success: function() {
// do something on success
},
error: function(jqXHR, textStatus, errorThrown) {
// do something on error
}
});
The POST call completes successfully with HTTP status 200. However, in the Firefox console the following is output:
no element found ... myscript.js:1
If I change my controller to return a boolean then this error disappears. However, according to this question having #ResponseBody on a method with void return type is valid.
Is there anything I can change to remove this message?
As described in the JQuery Bugs and in Firefox Bug, it is a Firefox problem that occurs when response entity body is null.
To fix it, you have to return such a ResponseEntity in your Controller method.
Try to add dataType: 'text' in your request:
$.ajax({
url: '/appserver/model/remove',
data: { value1: value1, value2: value2 },
type: 'POST',
traditional: true,
dataType: 'text',
success: function() {
// do something on success
},
error: function(jqXHR, textStatus, errorThrown) {
// do something on error
}
});
and modify your Controller to return a ResponseEntity with a String as first parameter
#RequestMapping(value = "/remove", method = RequestMethod.POST)
public ResponseEntity<String> remove(#RequestParam("value1") String value1,
#RequestParam("value2") String value2)
{
// do stuff
return new ResponseEntity<String>("OK!!!",HttpStatus.NO_CONTENT);
}