Reputation: 928
Can I use spring form tag library in conjunction with Ajax? I'm not able to retrieve the form input parameters inside the controller. They are always null.
Actually there is a logic that the form is never submitted. But then I can only send strings to my controller and not an object as happens with a form submit that gets mapped to a Spring commandBean.
Form accepting the commandBean
<form:form method="POST" commandName="clinicBean">
Clinic Name: <form:input path="name" type="text" /><br/>
Clinic Address: <form:input path="address" type="text"/><br/>
<input type="button" value="Create Clinic" onclick="clinicAjax()"/>
</form:form>
Ajax function calling the Spring controller
function clinicAjax(){
alert('Inside Clinic Ajax Method');
$.ajax({
url: 'clinicAjax',
type: 'POST',
success: alert('Ajax Successful')
});
}
Spring Controller method:
@RequestMapping(value="clinicAjax",method=RequestMethod.POST)
public @ResponseBody String createClinic(@ModelAttribute("clinicBean") Clinic clinic){
System.out.println("Ajax call successful");
System.out.println(clinic);
System.out.println(clinic.getName());
System.out.println(clinic.getAddress());
return "SUCCESS";
}
It always gets null in the System.out.println() statements.
Upvotes: 3
Views: 2913
Reputation: 36767
The problem is that you're not serializing your form anywhere so it's not being sent to the server.
Change your javascript code to:
function clinicAjax(){
alert('Inside Clinic Ajax Method');
$.ajax({
url: 'clinicAjax',
data: yourFormElement.serialize(); /* i.e. $('#formId').serialize(); */
type: 'POST',
success: alert('Ajax Successful')
});
}
substitute yourFormElement
with jQuery object representing your form and it should work.
Upvotes: 5