html form array to JSON

13,731

Solution 1

Well, you can use jQuery for it as it is easy to use and less code to write. Though i am giving both solutions here.

In JavaScript :

$.fn.extractObject = function() {
  var accum = {};
  function add(accum, namev, value) {
    if (namev.length == 1)
      accum[namev[0]] = value;
    else {
      if (accum[namev[0]] == null)
        accum[namev[0]] = {};
      add(accum[namev[0]], namev.slice(1), value);
    }
  }; 
  this.find('input, textarea, select').each(function() {
    add(accum, $(this).attr('name').split('.'), $(this).val());
  });
  return accum;
}
// ...

var object = $('#testformId').extractObject();
console.log(object);

​Here is the demo : http://jsfiddle.net/G2XVq/

In jQuery :

$.fn.serializeObject = function()
{
    var o = {};
    var a = this.serializeArray();
    $.each(a, function() {
        if (o[this.name] !== undefined) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};

$(function() {
    $('form').submit(function() {
        $('#result').text(JSON.stringify($('form').serializeObject()));
        return false;
    });
});​

(jQuery portion taken from here)

Here is the demo : http://jsfiddle.net/sxGtM/3/

for posting the data to php through javascript:

 var str_json = JSON.stringify(myObject) //gives me the JSON string.

// AJAX XMLHttpRequest object in Javascript to send data to the server:
request= new XMLHttpRequestObject()
request.open("POST", "Phppage.php")
request.setRequestHeader("Content-type", "application/json", true)
request.send(str_json)

Solution 2

The solution below utilizes the .map() function from jQuery to minimize the amount of code required to accurately reach your desired result.

HTML:

<input type="text" name="name" id="p" /> 
<input type="text" name="manuf" id="k" size="3" /> <input type="text" name="item_pr" id="ka" size="10" /> 
<input type="text" name="price" id="su" size="10" disabled="disabled"/>
<br /> 
<input type="button" id="go" value="Go >>" onclick="createJSONObject()" />

jQuery:

function createJSONObject(){
    var formValues = $('input[type=text]');
    var obj = {};
    $.map(formValues, function(n, i) {
        obj[n.name] = $(n).val();
    });

    console.log(JSON.stringify(obj));
}

Demo: http://jsfiddle.net/mBLkH/

The above code creates a jQuery object of your input elements and then maps the name attribute and value of each element to the obj object variable. It then utilizes JSON.stringify(obj) to format the object into a viewable context.

Share:
13,731
Osvalda Kazlaučiūnaitė
Author by

Osvalda Kazlaučiūnaitė

Updated on June 13, 2022

Comments

  • Osvalda Kazlaučiūnaitė
    Osvalda Kazlaučiūnaitė about 2 years

    I'm having a dynamic html form containing several values, what I need is to add form data to JSON and post it to php page for insertion to mysql.

    Form:

    <input type="text" name="name[]" id="p" />
    <input type="text" name="manuf[]" id="k" size="3" />
    <input type="text" name="item_pr[]" id="ka" size="10" />
    <input type="text" name="price" id="su" size="10" disabled="disabled"/><br />
    

    First tried to create JS array but cant figure out how get all values in one code row and how to convert to json and post to php:

    var elementai = document.getElementsByName('name[]');
              for (var i = 0, j = elementai.length; i < j; i++) {
              var elementas = elementai[i];
              alert(elementas.value);
              }
    
  • iambriansreed
    iambriansreed almost 12 years
    Overkill to use jQuery for this one instance.
  • iambriansreed
    iambriansreed almost 12 years
    Overkill to use jQuery for this one instance.
  • Nishu Tayal
    Nishu Tayal almost 12 years
    Even i don't suggest for using jquery for one instance only.That's why i have added javascript code here..
  • Osvalda Kazlaučiūnaitė
    Osvalda Kazlaučiūnaitė almost 12 years
    this is perfect. how to post it to php page? $.post should be in for cycle?
  • Nishu Tayal
    Nishu Tayal almost 12 years
    if there is going to be 50 form elements, then Is it good way to put all in input_id array one by one?????????
  • iambriansreed
    iambriansreed almost 12 years
    Your top example isn't pure JavaScript. :$
  • iambriansreed
    iambriansreed almost 12 years
    @NishuTayal With the HTML we were given this is my solution. Had we been given a form tag maybe with an ID then that would influence the answer. I work with what is asked for and what is given.
  • ssdscott
    ssdscott over 9 years
    I know it's been a while, PMJI - I am curious as to why you say jQuery is overkill. The Proof link seems to only prove that the js works - not why it's better. TIA for any info on this.