I have problems with sending my form using Ajax.
Here is form:
<form method="POST" id="add-card-form" action="${pageContext.request.contextPath}/card/add" class="form-horizontal">
<select name="type" class="form-control">
<c:forEach items="${cardTypes}" var="cardType">
<option value="${cardType.id}">${cardType.name}</option>
</c:forEach>
</select>
<select name="category" class="form-control">
<c:forEach items="${cardCategories}" var="cardCategory">
<option value="${cardCategory.id}">${cardCategory.name}</option>
</c:forEach>
</select>
<textarea type="text" name="description" class="form-control" rows="6"></textarea>
<input type="submit" id="add-card-submit" value="Add card" class="btn btn-primary"/>
Here is Ajax function:
$(document).on('submit', '#add-card-form', function(e) {
var frm = $('#add-card-form');
e.preventDefault();
var Form = this;
var data = {};
$.each(this, function(i, v){
var input = $(v);
data[input.attr("name")] = input.val();
delete data["undefined"];
});
//temporary solution
data["type"] = parseInt(data["type"]);
data["category"] = parseInt(data["category"]);
console.log(data);
if(frm.valid()) {
$.ajax({
contentType: "application/json; charset=utf-8",
dataType: "json",
type: frm.attr('method'),
url: frm.attr('action'),
data: JSON.stringify(data),
success: reloadBoard,
error: function (callback) {
console.log(callback);
}
});
refreshForm(frm);
}
});
And here is a controller action:
@RequestMapping(value="/add", method = RequestMethod.POST)
public @ResponseBody Card addCard(@RequestBody Integer type,
@RequestBody Integer category,
@RequestBody String description) {
Card card = new Card();
card.setType(cardTypeService.findById(type));
card.setCategory(cardCategoryService.findById(category));
card.setDescription(description);
card.setOwner(1);
cardService.saveCard(card);
System.out.println("Card with id " + card.getId() + " added!");
return card;
}
Variable data values:
Object {type: 1, category: 1, description: "New Card"}
When I try to send this form I always get error 400: http://localhost:8080/card/add 400 (Bad Request)
Can you tell me what is wrong with this code? I've ridden few posts, articles about sending data using Spring MVC + Ajax but no one helped.
Aucun commentaire:
Enregistrer un commentaire