Reputation: 2248
I'm trying to use an payment service API in my application and following the documentation provided on the website. According to the docs, the POST body should look like this:
api_hash=38be425a-63d0-4c46-8733-3e9ff662d62d
&hash=ac0945d82b8589959b5f4ffafcc1a6c5983e82b8b4094c377a7b9c43d4a432bc
&order_id=2845
&amount=15
¤cy=EUR
&[email protected]
&url_failure=http://my-test-store.com/order/fail
&url_ok=http://my-test-store.com/order/success
&items=[{"sku":"450","name":"Test Item","amount":"15","type":"item_type","qty":"1","price":15,"id":"5619","url":"http://example.com/products/item/example-item-name-5619"}]
I was able to successfully make a post request with postman however I'm confused about the "items" part in the post body since it's an object array. My html form looks like this:
<form method="post" action="@ViewBag.G2AConfig.PostUrl" id="g2apaymentform">
<!--PayPal Settings-->
<input type="hidden" name="api_hash" value="@ViewBag.G2AConfig.ApiHash" />
<input type="hidden" name="hash" value="@ViewBag.Hash" />
<input type="hidden" name="order_id" value="@ViewBag.OrderId" />
<input type="hidden" name="amount" value="@Model.Total" />
<input type="hidden" name="currency" value="USD" />
<input type="hidden" name="email" value="@ViewBag.G2AConfig.MerchantEmail" />
<input type="hidden" name="url_failure" value="@ViewBag.UrlFailure" />
<input type="hidden" name="url_ok" value="@ViewBag.G2AConfig.ReturnUrl" />
@foreach (var item in Model.Items)
{
<input type="hidden" name="items[@index][sku]" value="@item.Product.GameAccountId" />
<input type="hidden" name="items[@index][name]" value="@item.Product.Rank.Name" />
<input type="hidden" name="items[@index][amount]" value="@item.Product.MarketPrice" />
<input type="hidden" name="items[@index][qty]" value="1" />
index = index + 1;
}
</form>
I'm using Ajax post to make the request which looks like this:
event.preventDefault(); //prevent default action
var post_url = $(this).attr("action"); //get form action url
var request_method = $(this).attr("method"); //get form GET/POST method
var form_data = $(this).serialize(); //Encode form elements for submission
$.ajax({
url: post_url,
type: request_method,
data: form_data
}).done(function (response) { //
$("#server-results").html(response);
});
This does not work and I get bad error response from the server. What's the correct way to submit a form with an object array?
Upvotes: 0
Views: 672
Reputation: 5155
Why do you create a form with the supposed objects before posting it?
If there is no real reason other than posting the values then i suggest you build the AJAX data via a javascript array or PlainObject
as these are the other 2 possible data types for the data parameter. Currently you are using the serialized string.
Upvotes: 1