samedi 21 mars 2015

How to submit form with only checkboxes using ajax with modelAttribute

I have a form with only checkboxes. I use userForm.serialize() to get form data, however, the alert printed something like "male=true&female=on&status=true" when male and status are checked. The ajax call failed with "IN ERROR", server action is not invoked. How do I submit this form using ajax so that the model attribute gets the data from JSP ? Many Thanks.


Controller:



@RequestMapping(value = "/userSelectionSubmit", method = { RequestMethod.POST, RequestMethod.GET })
public ModelAndView userSubmit(@ModelAttribute UserSelections usersel)
{
boolean bMale = usersel.isMale();
boolean bFemale = usersel.isFemale ();
boolean bSingle = usersel.isSinlge();
}


JSP (sample):



<form:form id= "userForm" name="userForm" method="post"
modelAttribute="userSelections" action="UserSelectSubmit.htm">
<form:checkbox path="male" id="male" name="male" />male
<form:checkbox path="female" id="female" name="female" />female
<form:checkbox path="Single" id="Single" name="Single" />Single
<input id='btnContinue' type="button" value="Continue" />

<Script>
$(document).ready(function()
{
$("#btnContinue").click(function()
{
alert($("#userForm").serialize()); // this printed male=true&female=on&status=true

$.ajax({
type: 'POST',
url: "UserSelectSubmit.html",
contentType: "application/json",
data: $("#userForm").serialize()),
success: function(data)
{
.....
},
error: function(e)
{
alert('IN ERROR ');
}
});
})
})

Aucun commentaire:

Enregistrer un commentaire