User1v0 User1v0 - 2 months ago 6
Ajax Question

submit form ajax, receive null value in controller

I'm submitting a form to a spring controller using ajax, but when it reaches my controller I'm getting a null model, here I'm adding my code:





<script>
$(document).ready(function() {
$('#partsForm').submit(
function(event) {
var str = $("#partsForm").serialize();
$.ajax({
type : "POST",
url : $("#partsForm").attr("action"),
data : str,
dataType: "json",
contentType: "application/json"
});

return false;
});
});
</script>

<form:form id="partsForm" method="post" modelAttribute="modelpartsForm" class="form-horizontal" role="form" action="${pageContext.request.contextPath}/jsp/search/productConfig.html">
<div class="form-group">
<table class="table table-hover" width="50%" align="right">
<thead>
<tr>
<th></th>
<th>Part number</th>
<th>Price</th>
<th>Stock</th>
<th>Qty</th>
</tr>
</thead>
<tbody>
<c:if test="${!empty partsForm.prodls}">
<c:forEach items="${partsForm.prodls}" var="prodsByCat">
<tr>
<td></td>
<td>${prodsByCat.partNumber} ${prodsByCat.description}</td>
<td>${prodsByCat.price}</td>
<td>${prodsByCat.quantity}</td>
<td>
<input type="NUMBER" MIN="0" MAX=${prodsByCat.quantity} STEP="2" VALUE="0" SIZE="3">
</td>
</tr>
</c:forEach>
<tr>
<td colspan="5">
<button type="submit" class="btn btn-info">add parts</button>
</td>
</tr>
</c:if>
</tbody>
</table>
</div>
</form:form>





this is my controller



@RequestMapping(value="/productConfig",method = RequestMethod.POST)
@ResponseBody
public ModelAndView currentquote(@ModelAttribute("partsForm") PartsFormDTO partsForm) {
ModelAndView modelView = new ModelAndView();
....do some logic
return modelView;
}





when debugging I'm only getting a null partsForm, should I change my ajax call? Thanks!.

Answer

I found what the issue was, forgot to post the answer before, I wasn't actually submitting the model, since I have a list of products inside that model, I using varStatus="status" and passing them into the form, I'm passing them like hidden values,

	  <input type="hidden" name="prodls[${status.index}].partNumber" value="${prodsByCat.partNumber}"/>
      <input type="hidden" name="prodls[${status.index}].price" value="${prodsByCat.price}"/>
 

so that was first mistake, after that i was getting to my model, but instead of refreshing the DIV i wanted to update, it was redirecting me to the page view, so I had to modify my ajax call, like this:

$(document).ready(function() {
	$('#partsForm').submit(
		function(event) {
			var partsForm = "${partsForm}";

var str = $("#partsForm").serialize();
$.ajax({
	url : $("#partsForm").attr("action"),
	data : str,
	type : "POST",
	success : function(response) {
		$("#prodConfig").html(response);
	},
	error : function(xhr, status, error) {
		alert("ERROR:"+xhr.responseText);
	}	
});

After that it was getting to my controller and refreshing only the DIV I needed