1

In my abc.html I have the following code which will covert the form data(hard coded for now) to JSON format:

    <body>
    <form enctype='application/json' method="POST" name="myForm">

    <p><label>Company:</label>
    <input name='Company' value='TESTCOMPANY'> </p>

    <p><label>User Id:</label>
    <input name='User' value='TESTUSER'></p>

    <p><label>Division:</label>
    <input type="text" name='parameterMap[p1]' value='12345' ></p>

    <p><label>From:</label>
    <input type="text" name='parameterMap[p2]' value='20-MAR-2016'></p>

    <p><label>To:</label>
    <input type="text" name='parameterMap[p3]' value='22-MAR-2016'></p>

    <input value="Submit" type="submit" onclick="submitform()">
    </form>
    </body>

From the code above I get *

{"Company":"TESTCOMPANY","User":"TESTUSER","parameterMap":{"p1":"12345","p2":"20-MAR-2016","p3":"22-MAR-2016"}}*

Now I need to assign the Json String formed by this data to variable 'FormData' so that FormData is like:

FormData = '{"Company":"TESTCOMPANY","User":"TESTUSER","parameterMap":{"p1":"12345","p2":"20-MAR-2016","p3":"22-MAR-2016"}}'

How do I do this assignment of data ?

The further code in abc.html will use this variable FormData in the following way:

function sendAjax() {

    $.ajax({
        url : "myurl",
        type : 'POST',
        dataType : 'json',
        data : FormData,
        contentType : 'application/json',
        mimeType : 'application/json',
        success : function(data) {
            alert(data.uuid);
        },
        error : function(data, status, er) {
            alert("error: " + data + " status: " + status + " er:" + er);
        }
    });
    }
Jitendra Tiwari
  • 1,651
  • 3
  • 14
  • 28
NGB
  • 97
  • 1
  • 3
  • 13
  • Don't overwrite [the `FormData` global](https://developer.mozilla.org/en/docs/Web/API/FormData) (or use variables where the first letter is a capital for things which are not constructor functions) – Quentin May 04 '16 at 11:26
  • Your question, as it stands is very broad. An answer would need to cover fetching data from the DOM, converting it into the data structure you describe (which would mean special handling of fields with `[]` in the name), and encoding it as JSON. It would be a better question if you did some more research and narrowed it down to a more specific problem. – Quentin May 04 '16 at 11:29
  • You should [learn how to use the label element properly](http://www.456bereastreet.com/archive/200711/use_the_label_element_to_make_your_html_forms_accessible/). Without a for attribute or a form control inside it, a label is useless. – Quentin May 04 '16 at 11:30

4 Answers4

1

If you are not handling this in backend you can retrieve the data in Javascript in a variable then just appned it as JSON to your data using JSON.stringify().

This is a working snippet:

    function submitform() {
      var FormData = {
        Company: myForm.Company.value,
        User: myForm.User.value,
        parameterMap: {
          p1: myForm.p1.value,
          p2: myForm.p2.value,
          p3: myForm.p3.value
        }
      };
      console.log(FormData);

      $.ajax({
        url: "myurl",
        type: 'POST',
        dataType: 'json',
        data: JSON.stringify(FormData),
        contentType: 'application/json',
        mimeType: 'application/json',
        success: function(data) {
          alert(data.uuid);
        },
        error: function(data, status, er) {
          alert("error: " + data + " status: " + status + " er:" + er);
        }
      });
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form enctype='application/json' method="POST" name="myForm">

  <p>
    <label>Company:</label>
    <input name='Company' value='TESTCOMPANY'>
  </p>

  <p>
    <label>User Id:</label>
    <input name='User' value='TESTUSER'>
  </p>

  <p>
    <label>Division:</label>
    <input type="text" name='p1' value='12345'>
  </p>

  <p>
    <label>From:</label>
    <input type="text" name='p2' value='20-MAR-2016'>
  </p>

  <p>
    <label>To:</label>
    <input type="text" name='p3' value='22-MAR-2016'>
  </p>

  <input value="Submit" type="submit" onclick="submitform()">
</form>

Notes:

Use Javascript naming conventions, for example FormData will better be formData.

Community
  • 1
  • 1
cнŝdk
  • 31,391
  • 7
  • 56
  • 78
0

Using the provided HTML structure you could get the data into the format using:

function submitform(){
    var form = document.querySelector('form');
    var result = {};
    var input = form.getElementsByTagName('input');
    for(var i = 0; i < input.length; i ++) {
        var row = input[i];
        var rowName = ((row.name || '').match(/(\w+)(\[(\w+)\])?/) || []);
        var rowIndex = rowName[3];
        rowName = rowName[1];
        if(rowName) {
            var typeOfRowIndex = typeof rowIndex;
            var rowValue = row.value;
            if(typeof result[rowName] === 'undefined') {
                var rowToAdd = {};
                rowToAdd[rowIndex] = rowValue;
                result[rowName] = typeOfRowIndex === 'undefined' ? rowValue : rowToAdd;
            } else if(typeOfRowIndex !== 'undefined') {
                result[rowName][rowIndex] = rowValue;
            }
        }
    }
    document.getElementById('output').innerHTML = JSON.stringify(result)
    console.log(result);
    return false;
}
<body>
  <form enctype='application/json' method="POST" name="myForm">

    <p>
      <label>Company:</label>
      <input name='Company' value='TESTCOMPANY'>
    </p>

    <p>
      <label>User Id:</label>
      <input name='User' value='TESTUSER'>
    </p>

    <p>
      <label>Division:</label>
      <input type="text" name='parameterMap[p1]' value='12345'>
    </p>

    <p>
      <label>From:</label>
      <input type="text" name='parameterMap[p2]' value='20-MAR-2016'>
    </p>

    <p>
      <label>To:</label>
      <input type="text" name='parameterMap[p3]' value='22-MAR-2016'>
    </p>

    <input value="Submit" type="submit" onclick="return submitform()">
  </form>
  <p>JSON Output (after clicking submit button):</p>
  <div id="output"></div>
  <p>Can also check console to see JSON object (after clicking submit button)</p>
</body>
Moishe Lipsker
  • 2,974
  • 2
  • 21
  • 29
-1
var FormData = $('form[name=myForm]').serializeArray();
FormData = JSON.stringify(FormData);
Yordan Ivanov
  • 580
  • 4
  • 11
  • That will URL Encode it. The question is asking how to JSON encode it. – Quentin May 04 '16 at 11:26
  • Re edit: That will JSON encode the URL encoded string. It won't JSON encode the data structure that the question is specifically asking about. – Quentin May 04 '16 at 11:30
  • It is a POST request. It won't be URL encoded. Also it can be always be URL decoded into the backend. – Yordan Ivanov May 04 '16 at 11:31
  • "URL encoded" does not mean "Put in the query string", it means "encoded in the same way that is used for the query string". That string of URL encoded data can appear in the post body just as easily. I did misread the code though, I thought you used `serialize`, not `serializeArray`. `serializeArray` won't give the data structure requested though. – Quentin May 04 '16 at 11:33
  • I added the data the OP said they were expecting and compared them — https://jsfiddle.net/dr9jjfe0/2/ — it does not do what the question asks for. – Quentin May 04 '16 at 11:55
  • Ok. I Got it. It this case [that](https://jsfiddle.net/dr9jjfe0/3/) should do the job. – Yordan Ivanov May 04 '16 at 12:15
-1

I don't like jQuery, but:

var $inputs = $('form[name="myForm"]').find('input');

var res = {};
Array.prototype.forEach.call($inputs, function($item, index) {
  res[ $item.getAttribute('name') ] = $item.value;
});

var FormData = JSON.stringify(res);

alert(FormData);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
  <form enctype='application/json' method="POST" name="myForm">

    <p><label>Company:</label>
      <input name='Company' value='TESTCOMPANY'> </p>

    <p><label>User Id:</label>
      <input name='User' value='TESTUSER'></p>

    <p><label>Division:</label>
      <input type="text" name='parameterMap[p1]' value='12345' ></p>

    <p><label>From:</label>
      <input type="text" name='parameterMap[p2]' value='20-MAR-2016'></p>

    <p><label>To:</label>
      <input type="text" name='parameterMap[p3]' value='22-MAR-2016'></p>

    <input value="Submit" type="submit" onclick="submitform()">
  </form>
</body>
inomdzhon
  • 38
  • 6
  • That won't work. The data includes multiple fields with similar names that need to be expressed as sub-objects. – Quentin May 04 '16 at 11:34
  • I'm pretty sure that in that code `item` is a DOM object and not a jQuery object, so calling `val()` on it would throw an exception. – Quentin May 04 '16 at 11:35
  • @Quentin yes, thnx, I corrected it. P.S.: it's because i don't like jquery))) – inomdzhon May 04 '16 at 11:42