Receiving response as JSON in ajax call in jsp - ajax

I have a jsp page that sends response as a json. The page is requested through AJAX call. But the response went into Ajax error part instead of success part.
The resource identified by this request is only capable of generating responses with characteristics not acceptable according to the request "accept" headers
The following is my jsp page Script:
$("#Student").delegate("select[id='year.id']", "change", function () {
//alert("hi");
var id = $(this).attr('id');
var value=$("select[id='year.id']").val();
//alert(id);
//alert(value);
//console.log($(id).val());
$("select[id='classs.id']").empty();
$("select[id='classs.id']").append('<option value="">Select Class</option>');
$("select[id='section.id']").empty();
$("select[id='section.id']").append('<option value="">Select Section</option>');
$.ajax({
type: 'GET',
url: 'getStandard',
contentType: "application/json;charset=utf-8",
datatype: "Json",
data: { Year: value },
success : function(datas) {
$.each(datas, function (i, data) {
$("select[id='classs.id']").append('<option value="' + data.id + '">' + data.name + '</option>');
});
}
});
return false;
});
This Is my server side code where I am getting the response as Student object :
Controller :
#RequestMapping(value = "/getStudentName", method = RequestMethod.GET)
public #ResponseBody String getStudentName(#RequestParam("Year") String idYear, #RequestParam("Classs") String idClass, #RequestParam("Section") String idSection) throws JsonProcessingException
{
List<Student> student = userService.getStudentName(idYear,idClass,idSection);
return student ;
}
I am new to ajax using via Spring

#RequestParam is a parameter in the uri (http://uri?year=2018). If what you want is JSON then you should use #RequestBody instead

Related

ModelView, Ajax and Json return

In my code, i have two RequestMapper in my Controller which is designed this way :
#Controller
#RequestMapping("/myHostel.html")
public class HostelController
{
#RequestMapping(method = RequestMethod.GET)
public ModelAndView getText()
{
// do some cool stuff but not the point here
}
#RequestMapping(method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
#ResponseBody
public String getMyUrl()
{
String myVariable;
return "{\"myUrl\": \""+myVariable+"\""}";
}
}
And my ajax code :
function openNewTab() {
$.ajax({
url : 'myHostel.html',
type: "POST",
dataType: "json",
beforeSend: function(xhr) {
xhr.setRequestHeader("Accept", "application/json");
},
success : function(response){
console.log(response);
window.open(response.url, '_blank');
},
error: function(jqXHR, exception, errorThrown)
{
console.log(jqXHR.status);
console.log(exception);
console.log(errorThrown);
}
});
}
and my button is kinda like this :
<button tabindex="0" id="mySweetButton" class="btn btn-primary"
onclick="openNewTab();" >
Open a new tab
</button>
And what i get is :
200
parsererror
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
--
I've tried with putting a session variable in the model and a making a window.open(URL_IN_SESSION);
But if you reload the page, it's calling it again.
Making a c:remove on the variable when it's not used to cancel this problem but to no avail.
I have to get a variable from my ModelView after some previous call and open it in ajax (or javascript whatever as long as it works) to have my main page and my new tab with the custom URL.
If anyone has a idea on what i'm doing wrong ? (I need a custom URL made in my controller by previous GET call with user choices.)
Thank you for reading !
Solved by making just another GET requestMapping using no parameters and with value = ("/myHostel.html/getMyUrl.html")
One of the problem was the filters that only allowed .html url for the mapping.
The other was the JSON, just using :
#RequestMapping(method = RequestMethod.GET, value = "/getUrl.html")
public ResponseEntity<String> sendUrl()
{
return new ResponseEntity<>(getMyUrl(), HttpStatus.OK);
}
And parsing the return in ajax :
function openNewTab() {
$.ajax({
url : 'myHostel.html/getUrl.html',
type: 'GET',
dataType: 'text',
success : function(data){
window.open(data, '_blank');
}
});
}
And it solved the problem.

Put request into Spring Boot Controller

Im trying to send a json string with ajax to my spring boot controller but i keep getting the error net::ERR_TOO_MANY_REDIRECTS, and there are a bunch of $csrfError after the url. I've looked at tons of other websites and questions but I still can't get it to work. how do i correctly setup my ajax request so that my controller will accept the data?
ive already tried changing the method type to post and changing the RequestParams to ResponseBody but i went back to RequestParams
my ajax function
function deleteEvent() {
var startTime = document.getElementById('newStartTime').value;
var endTime = document.getElementById('newEndTime').value;
var type = document.getElementById('newTimeOffType').value;
var search = {startTime: startTime, endTime: endTime, type: type};
if(confirm("Are you sure you want to delete this event?")){
$.ajax({
method: 'PUT',
contentType: 'application/json',
url: '/vacation/deleteEvents',
dataType: 'json',
data: JSON.stringify(search),
success: function () {
console.log('success');
},
error: function (e) {
console.log(e);
}
})
}
else {
alert('you said no')
}
my spring controller
#RequestMapping(value = "/vacation/deleteEvents", method=RequestMethod.PUT)
#ResponseBody
public String deleteCalendarEvents(#RequestParam String startTime, #RequestParam String endTime, #RequestParam String type, HttpSession session ){
User user = (User) session.getAttribute("currentUser");
System.out.println("startTime: " + startTime);
System.out.println("endTime: " + endTime);
System.out.println("type: " + type);
return null;
}
i want it to print out the starttime, endtime, and type into my console but i keep getting this error.

How to send Long and Double through Ajax to Spring controller?

I want to send Long and Double to Spring controller use Ajax.
var id = $(this).data('customer-id');
var quantity = $('#quantity-' + id).val();
$.ajax({
headers: {
"Accept": "application/json",
"Content-Type": "application/json"
},
type: "POST",
url: '/changeQuantityOrder',
data: {idOrder: id, quantityChange: quantity},
error: function(e) {
console.log(e);
},
success: function (msg) {
window.location.href = "/administrationNotSleeps";
}
I try to receive a code so:
#RequestMapping(value = "/changeQuantityOrder", method = {RequestMethod.POST})
public #ResponseBody Long editCustomerOrder(#RequestParam(value = "idOrder")Long id,
#RequestParam(value = "quantityChange")Double quantity){
System.out.println("Id:"+id+" Quantity "+quantity );
return id;
}
But I receive exception
{"timestamp":1490775639761,"status":400,"error":"Bad Request","exception":"org.springframework.web.bind.MissingServletRequestParameterException","message":"Required Long parameter 'idOrder' is not present","path":"/changeQuantityOrder"}"
I looked for and have found about this exception (MissingServletRequestParameterException) https://stackoverflow.com/
But this article was written 3 years ago, maybe something changed?
Because now I send String to Spring controller and after that I use split in java.
key should be in quotes
data: {"idOrder": id, "quantityChange": quantity}
Also mention dataType - what kind of response to expect.

post ajax data to spring controller

I am a newbie to AJAX and i am trying to configure a simple method to post data into the controller using ajax only since i'm not sufficient in JSON
,lambda expressions other than Java can someone tell me what is the mistake i'm doing that this ajax method is not working?
Controller
#RequestMapping(value = "/test", method = RequestMethod.GET)
public String addCart(int val1, int val2) {
System.out.println("+++++++++++++++++++++++++++++" + val1);
System.out.println("+++++++++++++++++++++++++++++" + val2);
return "redirect:/viewResult";
}
Ajax/Script
$(document).on('change', '._someDropDown', function (e) {
var x = this.options[e.target.selectedIndex].text;
var y = $(this).data('idtest');
alert(x);
alert(y);
$.ajax(
{
url: "/HRS/test",
data: {val1: x, val2: y},
method: 'POST'
});
});
note that these alerts(x and y values) are shown correctly.I just want to send them to my controller.Please any suggestions?
First of all you need to make your Controller accept a POST Request which your AJAX code would be sending.
Then you need to add a RequestBody Annotation over the POJO that you wish to accept from AJAX.
Let's say you need to send var x, y. Create a class like this:
public class MyData {
String x;
String y;
// getters/setters/constructor
}
Then you need to create MyData in your AJAX Call & pass it.
$(document).on('change', '._someDropDown', function (e) {
var myData = {
"x" : this.options[e.target.selectedIndex].text,
"y" :$(this).data('idtest')
}
.ajax({
type: "POST",
contentType : 'application/json; charset=utf-8',
dataType : 'json',
url: "/HRS/test", //assuming your controller is configured to accept requests on this URL
data: JSON.stringify(myData), // This converts the payLoad to Json to pass along to Controller
success :function(result) {
// do what ever you want with data
}
});
Finally your controller would be something llike:
#RequestMapping(value = "/test", method = RequestMethod.POST)
public #ResponseBody String addCart(#RequestBody MyData data) {
System.out.println(data.getX());
System.out.println(data.getY());
return something;
}
My knowledge is a bit rusty but I hope you get the idea how this works!

Mapping Ajax Request in Spring MVC: getting error 405 method not allowed

After making the ajax call I am getting error 405 method not allowed. I am using Spring 3.0.1, Spring-web 3.0.1.
Here is the controller mapping
#Controller
public class AjaxController {
#RequestMapping(value = "/ajaxaction",
method = RequestMethod.POST,
headers ="content-type=application/json")
public #ResponseBody Collection<Employee> serveAjaxRequest(#RequestBody ReqParam reqParam){
List<Employee> empList = new ArrayList<Employee>();
System.out.println("Req obj:: " + reqParam.getA() + " " + reqParam.getB()
+ " " + reqParam.getC() + " " + reqParam.getD() + " " + reqParam.getE());
Employee e1 = new Employee();
e1.setFirstName("Vaibhav");
e1.setLastName("Raj");
e1.setEmail("vraj3#sapient.com");
e1.setTelephone("1111111111");
e1.setReturnMessage("Message one!!");
Employee e2 = new Employee();
e1.setFirstName("Ajay");
e1.setLastName("Singh");
e1.setEmail("asingh#gmail.com");
e1.setTelephone("2222222222");
e1.setReturnMessage("Message two!!");
empList.add(e1);
empList.add(e2);
return empList;
}
)
and the Jquery code for ajax call:
function : submitAjax(){
$('#g').bind('click', function(evt) {
alert($('form').serialize());
formData = $('form').serialize();
$.ajax({
url: "/ajaxaction.html",
type: 'POST',
dataType: 'json',
data: formData,
success: function(data) {
alert(data);
},
error: function(){
alert("Error!!");
}
});
});
From what the error tells, this may be your problem:
#RequestMapping(value = "/ajaxaction",
method = RequestMethod.POST,
headers ="content-type=application/json")
You can use firebug to check the request headers. Is there a header for "content-type"?
Try to set request content type using
contentType: 'application/json' in ajax options.
$('#g').bind('click', function(evt) {
alert($('form').serialize());
formData = $('form').serialize();
$.ajax({
url: "/ajaxaction.html",
type: 'POST',
dataType: 'json',
data: formData,
contentType: 'application/json',
success: function(data) {
alert(data);
},
error: function(){
alert("Error!!");
}
});
});
When using JSON response from Spring controller you need to define Accept header. By default Spring defines Accept header to html.
Add header:
headers = "Accept=application/json"
Modify your method annotation and change it like:
#RequestMapping(value = "/ajaxaction",
method = RequestMethod.POST,
headers ="Accept:*/*")
public #ResponseBody Collection<Employee> serveAjaxRequest(#RequestBody ReqParam reqParam)
Hi I got the same error and I fixed this by changing my Ajax call from get to post because I mentioned method as RequestMethod.POST in my #RequestMapping annotation same as you.
but I was making a get call to that method. check your ajax call
Enable Cross Origin Requests for a RESTful Web Service, take help from here

Resources