So I am using the play framework and trying to make and Ajax POST call to submit a JSON of product_id and quantity to my action that will add it to the current users cart. I have tried many different things and every time my JSON data is null in the controller. I am really stuck and cant figure out why.
HTML where the form I want to submit is:
@(product: Product)
<li data-task-id="@product.id">
<img src="@product.imageUrl" alt="No Image Available">
<h2>@product.name</h2>
<!-- Price Display -->
@if(product.price != 0.0){
<span class="product-price">@product.price</span>
<form name="ajaxform" id="ajaxform" action="@routes.Item.addToCart()" method="POST">
<input type="text" name="id" value="@product.id" hidden="true"/> <br/>
<input type="text" name="qty" value ="1" /> <br/>
<input type="submit" name="submit"/>
</form>
}
@if(product.price == 0.0){
<span class="available-in-store">Only Available in Store</span>
}
</li>
Here is my javascript:
$("#ajaxform").submit(function(e)
{
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax(
{
url : formURL,
type: 'POST',
dataType : 'json',
contentType:'application/json',
data : {postData: JSON.stringify(postData)},
success:function(data, textStatus, jqXHR)
{
},
error: function(jqXHR, textStatus, errorThrown)
{
}
});
//e.preventDefault(); //STOP default action
});
$("#ajaxform").submit(); //SUBMIT FORM
Yes I have tried making data : postData and not using stringify. It had the same result.
Here is my action in my controller that handles the request:
public static Result addToCart(){
JsonNode jsonNode = request().body().asJson();
if(jsonNode == null){
return badRequest("Expecting JSON data");
}
//Customer currCustomer = Customer.find.where().eq("email", session().get("email")).findUnique();
//System.out.println(cartItemForm.data().get("productId"));
//Product product = Product.find.byId(productId);
//ShoppingCart cart = new ShoppingCart(currCustomer, product, quantity);
//cart.save();
//currCustomer.shoppingCartList.add(cart);
return ok("Item Added to Cart");
}