When ajax call happens it shows error occurred without any tomcat error logs. While on browser is displays 400.
Here is my ajax call.
var data = {
"topic" : $("#topic").val()}
$.ajax({
type : "GET",
contentType : "application/json",
url : "./saveSyllabus",
data : JSON.stringify(data),
dataType : 'json',
timeout : 100000,
success : function(data) {
console.log("SUCCESS: ", data);
alert("Record Added Successfully!!")
},
error : function(e) {
console.log("ERROR: ", e);
alert("Error Occured!!")
},
done : function(e) {
console.log("DONE");
enableSearchButton(true);
}
});
Controller code:
#Controller
public class RegistrationController {
#Autowired
UserCreationService userCreationService;
#Autowired
SyllabusService syllabusService;
#RequestMapping(value="/saveSyllabus",method=RequestMethod.GET)
public #ResponseBody String saveSyllabus(#RequestParam String topic) {
System.out.println("in registration controller");
Integer id= syllabusService.saveSyllabus(syllabusDetails);
return id;
}
}
I have added required dependancies also:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
Your problem is the controller is configured to response in body, but your are doing a redirect, in your case it seems you want the redirect so remove the #ResponseBody:
#RequestMapping(value="/saveSyllabus",method=RequestMethod.GET)
public String saveSyllabus(#RequestParam String topic,RedirectAttributes rd) {
System.out.println("in registration controller");
Integer id= syllabusService.saveSyllabus(syllabusDetails);
if(id>0){
rd.addFlashAttribute("id", 1);
} else {
rd.addFlashAttribute("id",0);
}
return "redirect:"+ "/register";
}
As your are doing a redirect this sould be a browser URL call and not an Ajax call
Instead if you want to reponse to the body try this
var data = {
"topic" : $("#topic").val()}
$.ajax({
type : "GET",
contentType : "application/json",
url : "./saveSyllabus",
data : JSON.stringify(data),
dataType : 'json',
timeout : 100000,
success : function(data) {
console.log("SUCCESS: ", data);
alert("Record Added Successfully!!")
},
error : function(e) {
console.log("ERROR: ", e);
alert("Error Occured!!")
},
done : function(e) {
console.log("DONE");
enableSearchButton(true);
}
});
and
#RequestMapping(value="/saveSyllabus",method=RequestMethod.GET)
public #ResponseBody String saveSyllabus(#RequestBody String topic) {
System.out.println("in registration controller");
Integer id= syllabusService.saveSyllabus(syllabusDetails);
return String.valueOf(id);
}
note #ReuqestParam change to #RequestBody and the method content changed too
You're returning a String value from #Controller using #ResponseBody but your AJAX is expecting a JSON response from Controller datatype: 'json',. Change your AJAX Response expectation to HTML datatype : 'HTML', and it will return status 200!
Related
I'm trying to passing Json Data with Ajax to SpringBoot, but it's throwing error, What is the mistake in my program Pls tell me and suggest me. what is the mistake.
var emailId = {"emailId" : userEmail};
$.ajax({
url : "/api/v1/leadsquard/user/emailId",
type : "GET",
data : JSON.stringify(emailId),
dataType : "text",
contentType: "application/json",
success: function (response) {
alert("Success "+ JSON.stringify(response));
},
error: function(response) {
alert("Success "+ JSON.stringify(response));
}
});
Controller Class
#RestController
#RequestMapping(value = "/api/v1")
public class LeadSquardController {
#Autowired
LeadSquardService leadSquardService;
#GetMapping("leadsquard/user/emailId")
#ResponseBody
public String getByEmailaddress(#RequestBody Object emailId) {
System.out.println("Email : " + emailId.getClass().getName()); //Testing line
System.out.println("Email : " + emailId); //Testing line
return "";
}
}
Why are you using RequestBody when you are sending it as GET request. I would have used POST instead.
Use #PostMapping for your resource and make a POST ajax call.
My ajax call is
$.ajax({
type : "POST",
headers : {
'X-CSRF-TOKEN' : $("meta[name='_csrf']").attr("content")
},
url : url,
contentType : "application/json",
data : JSON.stringify(subdata),
success : function(data) {
alert("Added sussefull");
alert(data);
alert(data.message);
},
error : function() {
alert("in error");
}
});
my controller
#RequestMapping(value="/addcourse",method =RequestMethod.POST,produces = "application/json")
public #ResponseBody String addCourse(#RequestBody Subject subject)
{
String message = subjectService.addSub(subject);
return message;
}
Ajax call is not working if I am sending string value, if I changed string to void its working.
I am new to Spring MVC and I am trying to send my data to Spring-MVC Controller using AJAX, on button click. I have written this code (given below) but I am getting error instead of success. please tell what can be the issue?
AJAX:
function add() {
var name = $('#name').val();
$.ajax({
url : "/addUser",
data : name,
type : "POST",
async: false,
success : function(response) {
alert( response );
},
error : function() {
alert("error....");
}
});
}
JAVA
#RequestMapping(value = "/addUser", method = RequestMethod.POST)
public String addUser(#ModelAttribute("UserTest") String name) {
//task
return name;
}
I've read 3/4 posts on Stack plus many other examples to try figure this out but I've no clue ! Need some pointers please !!
Creating my first Ajax update through Spring-MVC and I keep getting a Status 415 being returned by my submission with The resource identified by this request is only capable of generating responses with characteristics not acceptable according to the request accept
JQuery... Version 3.1.1
function updateScore () {
$("div#results").append("<p>Posting User/Game ID " + this.id + " Value " + this.value + "</p>");
var prediction = {}
prediction["id"] = this.id;
prediction["value"] = this.value;
$.ajax({
type : "POST",
contentType : "application/json",
url : "/tournament/setPrediction.html",
data : JSON.stringify(prediction),
dataType : 'json',
timeout : 100000,
success : function(data) {
console.log("SUCCESS: ", data);
displayResult(data, "success");
},
error : function(e) {
console.log("ERROR: ", e);
displayResult(e, "error");
},
done : function(e) {
console.log("DONE");
displayResult(true, "done");
}
});
}
Controller... Spring version 4.3.5
#RestController
public class PredictionAjaxController {
#ResponseBody
#RequestMapping(value = "/setPrediction.html", consumes = MediaType.APPLICATION_JSON_VALUE,
method = RequestMethod.POST, headers="Accept=application/json")
public Prediction setUserPrediction(#RequestBody PredictionPojo prediction) {
Prediction result = new Prediction();
System.out.println("AJAX call made in controller");
return result;
}
}
Finally a very simple POJO for the JSon to map to
public class PredictionPojo {
private String id;
private String value;
Getters & Setters... ()
}
I've added different things onto the controller now to try and resolve, didn't start with it all ! I'm completely confuddled !
Should be so simple...
DH
You have an error in your ajax call, you are sending a string instead of a JSON object. Also I don't think is necessary to specify the consumes and headers attributes in you #RequestMapping annotation in your setUserPrediction method, The PredictionAjaxController is already defined as a RestController. Your ajax should be:
$.ajax({
// .......
data : prediction,
// .......
});
My spring controller contains such get handler :
#RequestMapping(value = "/country", method = RequestMethod.GET, produces = "application/json")
public #ResponseBody List<Region> getRegionsFor(#RequestParam(value = "countryName") String countryName,
#RequestParam(value = "geonameId") Long geonameId) {
logger.debug("fetching regions for {}, with geonameId {}", countryName, geonameId);
RegionInfo regionInfo = restTemplate.getForObject(
"http://api.geonames.org/childrenJSON?geonameId={geonameId}&username=geonameUser2014",
RegionInfo.class, geonameId);
return regionInfo.getRegions();
}
#Controller is mapped to /hostel. So url is /hostel/country?countryName=%27&Albania%27&&geonameId=783754
When I type in chrome browser
http://localhost:8080/HostMe/hostel/country?countryName=%27Albania%27&geonameId=783754
It returns json response as expected!!!
But I want to access this url with the following ajax call made with jquery:
$.ajax({
headers : {
'Accept' : 'application/json'
},
url : '/hostel/country',
dataType : 'json',
data : {countryName:"Albania",geonameId:783754},
type : 'GET',
async : true,
success : function(response) {
console.log("response=" + response.join(','));
},
error : function(errorData) {
console.log("data on fail ");
printObject(errorData);
}
});
As you guess this doesn't work at all. Http status 404 (Not Found) is returned to error: handler .
How can I solve this?
The url in the ajax call is relative to the hostname. You need to add your web application context
url : '/HostMe/hostel/country',