I am trying to POST to a Spring MVC controller method via ajax. Using Chrome's developer tools, I can tell that the values from the form are being sent, but in the method, the form values are null.
Here is the jquery call:
var form = $('#renegotiationForm').serialize();
$.ajax({
method:'POST',
url:'/renegotiate/wizard/startRenegotiation',
data:{'renegotiationForm': form},
success: function(data) { this.transitionTo(data); }
});
Here is the Spring MVC method (meant to return only a single string):
#RequestMapping(value="wizard/startRenegotiation", method = RequestMethod.POST)
public #ResponseBody String processStart(#ModelAttribute("renegotiationForm") RenegotiationForm form, BindingResult bindingResult) {
log.debug("Entered showStart(), method=POST");
RenegotiationType type = RenegotiationType.valueOf(form.getRenoType().trim().toUpperCase());
RenegotiationActivity activity = RenegotiationActivity.valueOf(form.getRenoActivity().trim().toUpperCase());
String result = "";
if (type == RenegotiationType.TYPE1 && activity == RenegotiationActivity.ACTIVITY1) {
result = "deleteType1";
}
return result;
}
The values are bound using the Spring Form taglib, and I have confirmed that the path attributes of the form tags match the fields of the RenegotiationForm.
I think it's because you are trying to send an "string" from ajax and you want to get and Object (RenegotiationForm), try to change it to String and Format in Server-side. I recommend you to add the type you are sending from client-side, too.
#RequestMapping(value = "wizard/startRenegotiation", method = RequestMethod.POST, produces="application/json")
Found the answer. Further on in my code, I had a function like this:
var ajaxcall = function() { $.ajax({
// ajax settings
});
}
Unfortunately, setting it up this way doesn't make it work as a jquery deferred, and specifically I couldn't use the .then() function to process of ajax requests.
Thanks for the help.
Related
I have a simple JSP file with some radios, one text input and one button.
In the button onClick I am doing an Ajax request to a Spring controller as you can see bellow:
function callFiltrarViaAJAX() {
var filtro = $("#filtro").val();
var optFiltro = $('input[name=optFiltro]:checked').val();
$.ajax({
type : "GET",
url : "filtrar",
//dataType : "json",
data : {
filtro : filtro,
optFiltro : optFiltro
},
success: function(data) {
console.log("SUCCESS: ", data);
},
error: function(e) {
console.log("ERROR: ", e);
},
done: function(e) {
console.log("DONE");
}
});
}
In the Spring controller I am receiving this request with success with the following code:
#Controller
public class FiltroController {
#RequestMapping(value = "/filtrar", method = RequestMethod.GET)
public #ResponseBody String filtrarVacina(FiltroTO filtro, HttpServletResponse response, ModelAndView model) {
VacinaTO v = new VacinaTO();
v.setId(new Long(10));
v.setLote("Lote 1");
v.setNome("BCG");
model.addObject("vacina", v);
response.setStatus(200);
return "TEST OK";
}
}
As you can see in the code above, I'm adding a POJO object in the ModelAndView that I'am trying to use in the JSP to show the return of the Ajax request in a table.
My Ajax request returns with success too but the problem is that even returning with success I can't use the POJO object, when I try to access the object by expression language I got nothing.
I've been searching about this situation and I found a lot of contents but none of the solutions that I've found works for me, but I found an interesting answer:
JSP inside ListItems onclick
So, is it means that I can't get a new parameter in the same JSP file with a Ajax request ? If yes, would be a JSON file the better way to get the return from the Spring controller ?
You can't access the model because you're returning an arbitrary string from controller instead of the view in which you want to access model.
If you're trying to access vacine from some.jsp, then you should return some from the controller method.
Of course, what I said is valid if you have proper ViewResolver configuration.
I am trying to create a RESTful service and encounter a type conflict within the application. Right now, I deal with this problem by using two different URLs, but this leads to other problems and doesn't feel right.
// Controller to get a JSON
#RequestMapping(value = "/stuff/{stuffId}",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
#ResponseBody
public stuffDto getStuff(#PathVariable String stuffId) {
return //JSON DTO//
}
// Controller to get an HTML Form
#RequestMapping(value = "/stuff/{stuffId}/form", // <- nasty '/form' here
method = RequestMethod.GET)
public String getStuffForm(#PathVariable String stuffId, ModelMap model) {
// Prepares the model
return "JSP_Form";
}
And on the JavaScript side:
function loadStuffForm(url) {
$.ajax({
type : 'GET',
url : url,
success : function(response) {
showStuffForm(response);
}
});
}
How can I merge both controllers so it will return the right type of data based on what the client accepts? By default it would return a JSON. I want to add 'text/html' somewhere in the ajax query to get the Form instead. Any idea?
You can use Content Negotiation to communicate to the server and tell it what kind of a response you're expecting form it. In your particular scenario, you as a client using an Accept header tell the server to serve a text/html or application/json. In order to implement this, use two different produces with that same URL:
// Controller to get a JSON
#ResponseBody
#RequestMapping(value = "/stuff/{stuffId}", method = GET, produces = "application/json")
public stuffDto getStuff( ... ) { ... }
// Controller to get an HTML Form
#RequestMapping(value = "/stuff/{stuffId}", method = GET, produces = "text/html")
public String getStuffForm( ... ) { ... }
In your requests to /stuff/{id} endpoint, if you send Accept: text/html in headers, the HTML form would return. Likewise, you would get the JSON response by sending Accept: application/json header.
I'm not a JQuery expert but you can check this answer out on how to send an Accept header in $.ajax requests.
I'm a little bit confused. I'm writing an MVC application and have a simple controller like this:
#Controller
public class ProfileController {
final String DEFAULT_MALE_AVATAR = "../resources/graphics/avatarMan.PNG";
final String DEAULT_FEMALE_AVATAR = "../resources/graphics/avatarWoman.PNG";
#Autowired
UserService userService;
#RequestMapping(value = "/profile", method = RequestMethod.GET)
public String index() {
return "user/profile";
}
#RequestMapping(value = "profile/getavatar", method = RequestMethod.GET)
public #ResponseBody String getLoggedUserAvatar() {
String userMail = SecurityContextHolder.getContext()
.getAuthentication().getName();
User loggedUser;
if (userMail != null) {
loggedUser = userService.findUserByEmail(userMail);
return loggedUser.getAvatar();
} else {
return DEFAULT_MALE_AVATAR;
}
}
I've also got a simple js file called with "onload" in my body html tag while entering /profile section.
function init() {
var url = "profile/getavatar";
$.ajax({
url : url
}).then(function(data) {
avatarLink = data;
loadAvatar(avatarLink);
});
function loadAvatar(avatarLink){
$("#userAvatar").attr("src", avatarLink);
}
}
And for some strange reason I get ridirected to "profile/getavatar" and the page contains text with value returned by getLoggedUserAvatar(). The funny thing is I've also got some other controllers to other sections with almost the same js files and controllers - and they work like a charm.
What am I missing?
I hope when you hit the URL directly, you are getting expected response. If that is not happening, then there is something else wrong. If you are getting proper response when you directly hit the url in browser, then try doing the below when doing the ajax call. It passes the content type that is expecting back from the server.
function init() {
var url = "profile/getavatar";
$.ajax({
url : url,
dataType: "json"
}).then(function(data) {
avatarLink = data;
loadAvatar(avatarLink);
});
function loadAvatar(avatarLink){
$("#userAvatar").attr("src", avatarLink);
}
}
If you are using spring 4, Please make sure that you have Jakson jars in your dependency library. framework will automatically pickup the content negotiator as JSON and will find for the Jakson jars in the background to transport JSON to server and get JSON data back from server
use JAXB jars , in case you need to handle XML as content negotiator.
Hiii Guys, I am working on a project which is using Spring MVC and Hibernate framework. My problem is that I am working on a Form and in the form a Option Box working. I want to change a text field value on change of option box value.
I already Try this :-
<script type="text/javascript" >
$(document).ready(function(){
$("#venderid").change(function(){
$.getJSON("getVenderById.htm", {venderId: $(this).val()},
function(vender){
var data = JSON.parse(vender);
var mail = data.email;
$("#mail").html(mail);
}
);
});
});
</script>
Vender.java
public class Vender {
private Integer venderid;
private String vendername;
private String email;
private String contact;
//Setters and getters
}
Controller:-
#RequestMapping(value = "/getVenderById.htm")
#ResponseBody
public ModelAndView getVender(#RequestParam("venderId") int vId){
ModelAndView mav = new ModelAndView();
mav.addObject("vender", venderDAO.findById(vId));
System.out.println("=========Ajax Calling============");
return mav;
}
Every thing is working fine but how to filled the textbox of e-mail according vender id . Is there any mistake in Callback function , or how to utilize the value of vender object. And one more thing on Apache server console window ========Ajax Calling======= printing means data is coming from the database. But how do i utilize it please help . And thanks in advance.
In you ajax callback handler you are expecting vendor, whereas you are sending MAV in your controller. Try doing this in your controller.
#RequestMapping(value = "/getVenderById.htm")
#ResponseBody
public Vender getVender(#RequestParam("venderId") int vId){
return venderDAO.findById(vId);
}
I would like to add to minion's answer you need to remove .htm as you are expecting JSON in response.
And it's a better practice to use ContentNegotiatingViewResolver and set JSON response as default.
Here is a link Content Negotiation using Views at spring.io
Please debug or console.log the vender value in the callback like this:
function(vender){
console.log(vender);
var data = JSON.parse(vender);
var mail = data.email;
$("#mail").html(mail);
}
Then copy the value here
I'm trying to make a simple AJAX call in my Spring MVC project but am running into trouble. I am making my AJAX request by sending an String type argument and I'm wanting to get an ArrayList type back. I've read many tutorials at this point and can't figure out what's wrong with my AJAX/Controller configuration. I am using the ResponseBody annotation when trying to return my needed result back to the view. In this controller I am not returning an updated ModeAndView object, but this shouldn't matter since the page does not need to be refreshed because I'm using AJAX. Below is my AJAX call and controller code. I would really appreciate it if someone could give me a hint on what I'm doing wrong here.
function getdays() {
var monthSelected = $("#monthselect option:selected").text();
alert(monthSelected);
$.ajax({
url : '${pageContext.request.contextPath}/ajaxdays',
data: monthSelected,
success : function(data)
{
$('#daySelect').html(data);
alert(data);
}
});
}
Here is my controller class:
#Controller
#SessionAttributes
public class WorkstationController
{
#RequestMapping(value = "/ajaxdays", method = RequestMethod.GET)
public #ResponseBody
ArrayList<String> getTime(HttpServletRequest request)
{
ArrayList<String> retList = new ArrayList<>();
retList = this.getList();
return retList;
}
}
you have following errors
wrong url
change url : 'ajaxdays.html'to ${pageContext.request.contextPath}/ajaxdays
no parameter passed
you are not passing any data to server side so there is no need to write data: monthSelected
URL mentioned in ajax call should be the context path followed by the controller mapping. And '.html' should not be specified.
url: ${pageContext.request.contextPath}/ajaxdays