Error 415 with ajax request (Spring) - ajax

My ajax request gets sent but never reaches my conrtroller, I get a 415 Error ()
The Ajax Request
function likeAjax(mId) {
var data = {}
data["id"] = mId;
$.ajax({
type : "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
url : "/likeMessage",
data : JSON.stringify(data),
dataType : 'json',
timeout : 100000,
beforeSend :(xhr)=>{
xhr.setRequestHeader(csrfheader,csrftoken); //for Spring Security
},
success : (data) =>{
console.log("SUCCESS : ", data);
alert(data);
},
error : (e)=> {
console.log("ERROR: ", e);
},
done : function(e) {
alert("DONE : " + e.toString());
console.log("DONE");
}
});
The controller
#ResponseBody()
#RequestMapping(value = "/likeMessage", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
public AjaxResponseBody likeWithAjax(#RequestBody() AjaxRequestBody request) {
AjaxResponseBody result = new AjaxResponseBody();
//some logic
return result
}
The AjaxRequestBody and AjaxResponseBody classes
private class AjaxRequestBody{
int id;
}
private class AjaxResponseBody{
String message;
}
I'm sure that I am missing something obvious but I can't seem to figure this one out.
Thank you for your help

Remove ResponseBody() annotation from the Controller Method. Make sure you have added RestCOntroller annotation in the Controller Class.
Add produces = "application/json" in RequestMapping

Related

How to download a file from an AJAX response

Im making an AJAX POST request to a spring controller and getting returned an byte array as the response. I want to make it downloadable. What is the best approach to take?
Heres my implementation :
var params = [[${params}]];
$("#download-button").click(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
contentType: "application/json",
url: "/patient-listing/excel",
data: JSON.stringify(params),
success: function(result) {
var byteArray = result;
var a = window.document.createElement('a');
a.href = window.URL.createObjectURL(new Blob([byteArray], { type:'application/octet-stream' }));
a.download = "file.XLSX";
document.body.appendChild(a)
a.click();
document.body.removeChild(a)
},
error: function(result) {
console.log('error');
}
});
});
In here even though the file is downloaded there is no data.
Controller :
#PostMapping(value = "/patient-listing/excel", consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity getEmployeeReportXlsx(#RequestBody Param param) {
logger.info("Generating Excel report of param : " + param);
final byte[] data = poiService.getExcelFile(param);
HttpHeaders header = new HttpHeaders();
header.setContentType(MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"));
header.set(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=case-data-report.xlsx");
header.setContentLength(data.length);
return new ResponseEntity<>(data, header, HttpStatus.OK);
}
You can simply download excel without AJAX request,
Change POST method to GET method using #GetMapping
#GetMapping(value = "/patient-listing/excel", consumes = MediaType.APPLICATION_JSON_VALUE)
in thymeleaf ,
<a class="sidebar-element" th:href="#{/patient-listing/excel}">
Generate Excel
</a>

How to send post ajax request from (.js) file to Spring MVC Controller?

(.js)
$.ajax({
type: "POST",
//contentType : "application/json",
dataType : "json",
url: "getStateNames",
//url:"http://localhost:8081/Mining_22_11_17/pages/admin/a.jsp",
cache: false,
data: "region=" + re + "& stId=" + state_id,
success: function(response){
//$('#result').html("");
alert("hiiii state list");
var obj = JSON.parse(response);
alert("state list" + obj);
//$('#result').html("First Name:- " + obj.firstName +"</br>Last Name:- " + obj.lastName + "</br>Email:- " + obj.email);
},
error: function(){
alert('Error while request..');
}
});
Spring MVC Controller
#RequestMapping(value="/getStateNames",method = RequestMethod.POST)
public #ResponseBody RegionDistrict add(HttpServletRequest request, HttpServletResponse response,#RequestParam String region, #RequestParam String stId) {
System.out.println("Get state");
}
By running this program I am getting 404 error.I want to send request using POST only.
$("#yourID").click(function(event) {
var region = $('#id').val();
var state_id = $('#edited').val();
$.post("${pageContext.request.contextPath}/getStateNames", {
region : region ,
state_id : state_id
}, function(data) {
//var json = JSON.parse(data);
//...
}).done(function(data) {
alert("hiiii state list");
swal("success");
//location.reload();
}).fail(function(xhr, textStatus, errorThrown) {
}).complete(function() {
//$("#btn-save").prop("disabled", false);
});
});
try this hope its works fine
$.ajax({
type: "POST",
url: "/getStateNames",
data: { region: re, stId: state_id },
success : function(response) {
alert(JSON.stringify(resoinse));
},
error: function(){
alert('Error while request..');
}
});
This should work, tell me if this solves your problem

spring Rest call through ajax

I am stuck with a problem when i send POST request through ajax to Spring Rest i am getting following error. But it is working fine with Postman tool.
How to solve this? Please help.
#RestController
public class LoginController {
#Autowired
LoginServiceBo loginServiceBo;
public void setLoginServiceBo(LoginServiceBo loginServiceBo) {
this.loginServiceBo = loginServiceBo;
}
#RequestMapping(value="/login",method = RequestMethod.GET)
public ModelAndView redirectLoginForm() {
System.out.println("Login Page...");
return new ModelAndView("login");
}
#RequestMapping(value="/login",method=RequestMethod.POST, consumes=MediaType.APPLICATION_JSON_VALUE, produces=MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Login> login(#RequestBody Login login) {
System.out.println("Checking Login Credentials...");
boolean isValid=loginServiceBo.checkUserLogin(login);
if(isValid) {
System.out.println("Found...");
return new ResponseEntity<Login>(login, HttpStatus.ACCEPTED);
}
System.out.println("Not Found...");
return new ResponseEntity<>(login, HttpStatus.NOT_FOUND);
}
}
In javascript
function RestPost() {
userId = document.getElementById("userId");
password = document.getElementById("password");
var json = {
"userId": userId,
"password": password
};
$.ajax({
url: prefix + "/login",
type: 'POST',
data: JSON.stringify(json),
cache: false,
dataType: 'json',
beforeSend: function(xhr) {
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");
},
success: function(response) {
alert(JSON.stringify(response));
},
error: function(jqXhr, textStatus, errorThrown) {
alert(jqXhr.status + ' ' + jqXhr.responseText);
}
});
}

405 error while calling webapi get method using ajax

I developed a WebApi and Client page for testing.
Here is my controller
public class CarDetailsController : ApiController
{
// GET api/cardetails
[HttpGet]
public IEnumerable<CarsStock > GetAllcarDetails()
{
CarsStock ST = new CarsStock();
CarsStock ST1 = new CarsStock();
List<CarsStock> li = new List<CarsStock>();
ST.CarName = "Maruti Waganor";
ST.CarPrice = "4 Lakh";
ST.CarModel = "VXI";
ST.CarColor = "Brown";
li.Add(ST);
ST1.CarName = "Maruti Swift";
ST1.CarPrice = "5 Lakh";
ST1.CarModel = "VXI";
ST1.CarColor = "RED";
li.Add(ST1);
return li;
}
}
and here is my ajax call
<button onclick="AllcarDetails()"></button>
<script type="text/javascript">
function AllcarDetails()
{
$.ajax({
type: "GET",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
contentType: 'application/json',
url: "http://localhost:1822/api/cardetails", //URI
success: function (data) {
debugger;
var datadatavalue = data;
},
error: function (xhr) {
alert(xhr.responseText);
}
});
}
</script>
It gives 405 Method Not Allowed error all the time.I tried by googling but cannot find the exact situation.Can somebody help me to solve this?
Got result correctly while calling from browser 'http://localhost:1822/api/cardetails'
Did you check so that HTTP Activation is activated where you run this code?

400 Bad Request while firing ajax

In ftl file, I have ajax like this here while firing ajax, I get 404 Not found error, though all things fine,
$.CustomService.execute("/policyDetails/"+$(this).attr('data-cancel-id')+"/policyList.json", {
method : "GET",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
success : function(response) {
alert("Success");
console.log(response);
},
error : function() {
alert("Error");
}
});
In Controller
#Controller
#RequestMapping("/cancellationPolicyDetails")
{
..........
..........
#RequestMapping(value = "/{id}/policyList", method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE})
#ResponseBody
public CancellationPolicyDetailDTO getDetails(#PathVariable Long id) {
return this.service.findOne(id);
}
}

Resources