I have a form whose input I would like to submit to an API in order to obtain a parseable response. So far I have managed to perform the request with a pre formatted object. However, I am having difficulty getting the format required to make the requests.
The structure of the request needs to look like this:
{ "request": { "slice": [ { "origin": "LAX", "destination": "BOS", "date": "2015-09-09" } ], "passengers": { "adultCount": 1 }, "solutions": 1 } };
I have changed the names of the form in an attempt to create the nested keys but what I get is:
{"request[slice][origin]":"LAX","request[slice][destination]":"BOS","request[slice][date]":"2015-09-09","request[passengers][adultcount]":"1","request[solutions]":"1"}
The form looks like this:
<form id="request" action="" onsubmit="request" method="post">
<input type="text" name="request[slice][origin]" placeholder="From">
<br>
<input type="text" name="request[slice][destination]" placeholder="Destination">
<br>
<input type="text" name="request[slice][date]" placeholder="Outbound Date">
<br>
<input type="text" name="request[passengers][adultcount]" placeholder="Passengers">
<br>
<input type="text" name="request[solutions]" placeholder="Results">
<br>
<p><input type="submit" /></p>
</form>
The script that serialises the object is:
<script>
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
$(function request() {
$('form').submit(function() {
$('#result').text(JSON.stringify($('form').serializeObject()));
return false;
});
});
</script>