0

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.

urbz
  • 2,663
  • 1
  • 19
  • 29
ninja.stop
  • 410
  • 1
  • 10
  • 24

3 Answers3

0

Form your own JSON rather than using $("#form");, Like

     var sensorArr=new Array();
    //push your values to SensorArr
     var data= {
        "version": $("input[name='version']").val(),
        "sensors": [
            {
                "sensor": "sensorID",
                "output": sensorArr;
            }
        ]
    }

and send this data to AJAX

Jayanth
  • 329
  • 4
  • 15
0

how about change html?

<input name='sensors[0][sensor]' value=''>

to

<input class="d_sensors" name='sensor' value=''>

read javascript

var data = {};
data['version'] = $("input[name='version']").val();
data['sensors'] = [];
var sensorsList = $(".d_sensors");
for (var i = 0; i < sensorsList.length; i++) {
  var $item = sensorsList.eq(i);
  var sensor = {};
  sensor['sensor'] = $item.val();
  sensor['output'] = [];
// do same way
}
Dongin Min
  • 409
  • 3
  • 5
  • 12
0

Will in your case you need to setup JSON Object , why !!

because when Html inputs submitted as Array each key mean new array you cannot group them in one object as you requested , to do this you need to use custom javascript array

this is full working example to your case

1- first : remove array name from your inputs to be like this :

  <input name='sensors_sensor' value=''>
  <input name='sensors_name' value=''>
  <input name='sensors_type' value=''>

2- second : add this object inside form post request ( AJAX )

  var fromData = { 
  "version"  : $('input[name=version]').val(),
  "sensors"  : [ { "sensor" : $('input[name=sensors_name]').val(),
                   "output" : [{  "name" : $('input[name=sensors_name]').val() , 
                                  "type": $('input[name=sensors_type]').val()}] } ],

  };

3- third : if you like to add more inputs just add it inside the formData object

4- finally : add formData object to your Ajax form and enjoy

$.ajax({
            url: "http://posttestserver.com/post.php",

            type: "POST",
            data: formData,
            success: function (send, status, jqXHR) {
                alert(JSON.stringify(send));
            },
Kodr.F
  • 13,932
  • 13
  • 46
  • 91
  • Hi, the json output is valid but after posting in server it is showing this error: {"readyState":4,"responseText":"","status":400,"statusText":"Bad Request"} – ninja.stop Aug 13 '14 at 11:07
  • check this link , this is another issue , http://pcsupport.about.com/od/findbyerrormessage/a/400error.htm – Kodr.F Aug 13 '14 at 12:35