I am trying to post some data from an HTML form to an webserver. Requirement is, The POST data should be a JSON data. The expected JSON from server is
{
"version": "1.0.1",
"sensors": [
{
"sensor": "sensorID",
"output": [
{
"name": "sensorName",
"type": "sensorType"
}
]
}
]
}
were sensorID
, sensorName
, sensorType
corresponds to the input fields from HTML form. Others should be as it is. My code is:
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
<h2>Create Sensor</h2>
<form id="form">
<form enctype='application/json'>
<input name='version' value='1.0.1'>
<input name='sensors[0][sensor]' value=''>
<input name='sensors[0][output][0][name]' value=''>
<input name='sensors[0][output][0][type]' value=''>
<br>
<input id="input" type="submit" name="submit" value="Create Sensor" />
</form>
<script>
$.ajaxSetup({
contentType: "application/json; charset=utf-8",
dataType: "json"
});
$(document).ready(function () {
$('#input').click(function () {
var send = JSON.stringify($("#form").serializeArray());
alert(send);
$.ajax({
url: "http://posttestserver.com/post.php",
type: "POST",
data: send,
success: function (send, status, jqXHR) {
alert(JSON.stringify(send));
},
error: function (jqXHR, status) {
alert(JSON.stringify(jqXHR));
}
});
return false;
});
});
</script>
</body>
</html>
I am having this output:
[{
"name": "version",
"value": "1.0.1"
}, {
"name": "sensors[0][sensor]",
"value": ""
}, {
"name": "sensors[0][output][0][name]",
"value": ""
}, {
"name": "sensors[0][output][0][type]",
"value": ""
}]
Can anyone please Help me out? I am trying hard. But as I am new to this, probably missing something that's why not able to solve this problem. It will be very helpful for me if anyone please guide me regarding this. Thanks in advance.