AJAX Call not Getting to Spring MVC Controller - java

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

Related

Ajax pass data to a URL

I wonder if someone could help me out please? What I'm trying to achieve (via ajax) is to pass parameters to a URL but not on the query string as I don't want to expose the parameters.
So I have a page which contains an Index method:
public ActionResult Index(int qualID)
{
//do stuff with qualID and load up a model
return PartialView("ICTEnrolmentForm", myNewModel);
}
and on (a completely separate page) I have the following block of ajax:
<script>
var enrolmentURL = "/enrolment/";
$('.enrolNow').click(function (e) {
var qualID = $(this).attr('data-qual');
$.ajax({
url: enrolmentURL,
type: 'POST',
data: { 'qualID': qualID },
success: function(model)
{
window.location = enrolmentURL;
}
});
});
</script>
If if create a breakpoint on the ActionResult method I can see that the method is being called (with the QualID populated) but then the redirect is fired and I'm getting an Null parameter error.
I'm obviously being really dim but if someone could point out the error of my ways that'd be much appreciated.
Thanks,
C
if you use spring boot, add this in your controller:
#RequestMapping(value = "/enrolment/",method = RequestMethod.POST)
public ActionResult Index(#RequestParam(value = "qualID" , required = false) String qualID)
{
//do stuff with qualID and load up a model
return PartialView("ICTEnrolmentForm", myNewModel);
}
I assume this is C# code and not Java, as mentioned in the TAG section?
The problem is that qualID can be NULL if you invoke the controller method via HTTP. However, qualID has the datatype Int32 which can't be null. So you have to change the datatype and the method signature to
public ActionResult Index(int? qualID)
Now, qualID is allowed to be NULL(you have to check this before you use the variable in your code and throw an appropriate error message). Additionally, check your defined routes.
not sure if this an answer or not but I've found a workaround basically I do an ajax post to another method which populates the model and puts the model into a session variable then upon success I'm doing the redirect to the URL which loads the session model onto the page.
The URL stays clean which is the main thing that I was after.
Thanks for your time folks.

Can I get a POJO in an Ajax Request to a Spring Controller?

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.

Ajax call to Spring MVC controller redirects page instead of returning value

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.

Spring MVC #ModelAttribute Not Binding Form

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.

Resolving view from ajax request using spring 3

Jquery code to call my spring controller:
$.postJSON("/DialogController", myJSON, function(data) {
previewDialog.html(data);
previewDialog.dialog('open');
});
And then my controller code, which causes a http 500 error, I have debugged it and find it all works fine until the return string(view name), what am I doing wrong ?
#RequestMapping(value = "/DialogController", method = RequestMethod.POST)
public String dialogController(Model model, #RequestBody MyClass myClass) {
myClass.setTitle("SUCCESS");
model.addAttribute("myClass", myClass);
return "dialogContent";
}
Using jquery load with get request on the controller works to an extent - in that it returns the view and loads into dialog; but the attribute is not added to model and I can not post json data to the controller.
Any tips ?
Have you tried putting #ResponseBody in your Controller? More information on this annotation is here: http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/mvc.html#mvc-ann-responsebody

Categories

Resources