Skip to content Skip to sidebar Skip to footer

Add Object Array To Form Object

I have a html form like this:
Copy

You can use it later in ajax. Or if you are not using ajax; put it in hidden textarea and pass to server. If this data is passed as json string via normal form data then you have to decode it using json_decode. You'll then get all data in an array.

$.ajax({
  type: "POST",
  url: "serverUrl",
  data: formData,
  success: function(){},
  dataType: "json",
  contentType : "application/json"
});

Reference : How to send a JSON object using html form data

Solution 2:

There is few ways this can be done, but here is the simpliest one

var rating = 0;

document.getElementById('addRating').addEventListener('click', function () {
  var ratingsElem = document.getElementById('ratings');

  var sourceElem = document.createElement("input");
  sourceElem.setAttribute('type', 'text');
  sourceElem.setAttribute('placeholder', 'Source');
  sourceElem.setAttribute('name', 'Ratings[' + rating + '][Source]');

  var valueElem = document.createElement("input");
  valueElem.setAttribute('type', 'text');
  valueElem.setAttribute('placeholder', 'value');
  valueElem.setAttribute('name', 'Ratings[' + rating +  '][Value]');

  ratingsElem.appendChild(sourceElem);
  ratingsElem.appendChild(valueElem);

 rating++;

});

If you want to do it without adding variable rating, on each new input for source you can calculate his index and than add input value with same index...

I hope this was helpful...

Here is output when I tested:

{"title":"","toYear":"","genre":"","director":"","poster":"","plot":"","Ratings":[{"Source":"1","Value":"2"},{"Source":"2","Value":"3"}]}

Post a Comment for "Add Object Array To Form Object"