1

I have a page on my web application where I'm trying to create a Person object, which I'm doing through an AJAX POST. The format of the JSON I need to send that the API endpoint is expecting is:

{
    "categoryId": "string",
    "name": "string",   
}

which is easily achievable with this HTML markup:

<form id="form">
    <input name="categoryId" value="..." type="hidden" />

    <input name="name" type="text" />

    <button type="submit">Create</button>
</form>

and then just serializing the data to be passed along with $('#form').serialize()

The problem is that my requirements have changed, and I need to send additional information along - a child collection on the Person. The API endpoint is now expecting this:

{
  "categoryId": "string",
  "name": "string",
  "aliases": [
  {
      "aliasName": "string",
      "position": 0
  },
  {
      "aliasName": "string",
      "position": 0
  },
  {
      "aliasName": "string",
      "position": 0
  }]
}

I'm not sure how I'm supposed to format my HTML markup to accommodate for this. I could set name="aliasName" and name="position" on several textboxes, but how can I group them together, and under a parent aliases?

Steven
  • 18,761
  • 70
  • 194
  • 296

1 Answers1

1

You can try using jquery-serialize-object

Example below:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-serialize-object/2.5.0/jquery.serialize-object.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
      var json = JSON.stringify($("#my-form").serializeObject());
      console.log(json);
      //alert(json);
      $("#divId").text(json);
    });
});
</script>
</head>
<body>

<form action="" name="my-form" id="my-form">
  some ID: <input type="text" name="someId" value="1"><br>
  First name: <input type="text" name="user[0][FirstName]" value="Mickey1"><br>
  Last name: <input type="text" name="user[0][LastName]" value="Mouse1"><br>
   First name: <input type="text" name="user[1][FirstName]" value="Mickey2"><br>
  Last name: <input type="text" name="user[1][LastName]" value="Mouse2"><br>
  <div id="divId"></div>
</form>

<button>Serialize form values</button>

<div></div>

</body>
</html>

CDN:

https://cdnjs.cloudflare.com/ajax/libs/jquery-serialize-object/2.5.0/jquery.serialize-object.min.js

Stackoverflow question in similar lines:

Convert form data to JavaScript object with jQuery

Hope it helps.

Shiva
  • 1,962
  • 2
  • 13
  • 31