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`
Related
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 :)
I have the following controller:
#RequestMapping(value = { "/member/uploadExternalImage",
"/member/uploadExternalImage" }, method = RequestMethod.POST)
public String handleFileUpload(#RequestParam("url") String url,
Principal principal) throws IOException {
File file = restTemplate.getForObject("url", File.class);
file.toString();
return null;
}
And I have the following ajax:
$.ajax({
url: 'uploadExternalImage', //Server script to process data
type: 'POST',
success: function () {
},
complete:function(){
$.fancybox.hideLoading();
},
// Form data
data: {url: files[0].link},
cache: false,
contentType: false,
processData: false
});
in spring log I see that
org.springframework.web.bind.MissingServletRequestParameterException: Required String parameter 'url' is not present
if I change ajax method with GET:
$.ajax({
url: 'uploadExternalImage?url=123', //Server script to process data
type: 'POST',
success: function () {
},
complete:function(){
$.fancybox.hideLoading();
},
error: function (data) {
},
cache: false,
contentType: false,
processData: false
});
it works fine
How does to configure spring correctly?
Http POST is capable of being used for request parameters on request body. But you are trying to use it on a different way.
Try this:
$.ajax({
type: 'POST',
url: "uploadExternalImage?url=BLABLA",
data: text,
success: function (data) {
//
}
});
If you want it on request body then use #RequestBody
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 have the restful webservices call from the Jquery ajax and getting the response in json object.
Jquery HTML:
$.ajax({
url: "mcrs/object/api/Lighting",
type: "POST",
traditional: true,
dataType: "json",
contentType: "application/x-www-form-urlencoded",
async: "false",
data:JSON.stringify(postdata),
success: function (ResData) {
},
error: function (error, data) {
console.log(error);
}
});
}
});
And writing the response object for the restful webservices in java
#POST
#Path("api/{subsystem}")
#Produces("application/json")
public Response changeStatus(#PathParam("subsystem") String subsystem,
/*#FormParam("result")*/ String result) {
}
I got the response below and which is correct
changeStatus:88 - Reponse OutboundJaxrsResponse{status=200, reason=OK, hasEntity=true, closed=false, buffered=false}
Depending upon the reponse need to update the status whether the value is on/off in the label tag.
str = ' Status : ' + '' + onoffStat + '';
How can I achieve this in ajax and want to have the refreshing the div tag for every 2 seconds.
Please help me.
You will have to use Javascript polling. Try out something like this:
function ajaxPoll(){
$.ajax({
url: "mcrs/object/api/Lighting",
type: "POST",
traditional: true,
dataType: "json",
contentType: "application/x-www-form-urlencoded",
async: "false",
data:JSON.stringify(postdata),
success: function (ResData) {
tag.str = 'Status : ' + '' + ResData.status + '';
},
error: function (error, data) {
console.log(error);
}
});
}
});
}
setInterval(ajaxPoll, 2000);
Hope you sort it out :)