2

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);
          }
  • I got hammered once for offering a jQuery solution where it wasn't asked for. So with that in mind check [this](http://stackoverflow.com/a/11419600/144665) out. – iambriansreed Jul 10 '12 at 18:31
  • 1
    Why use JSON? What is wrong with application/x-www-form-urlencoded data? Especially since you are already using the naming convention that allows PHP to handle multiple sets of inputs with the same name in that encoding. – Quentin Jul 10 '12 at 18:49

4 Answers4

4

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)
Community
  • 1
  • 1
Nishu Tayal
  • 20,106
  • 8
  • 49
  • 101
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.

Robert
  • 8,717
  • 2
  • 27
  • 34
0

jQuery is over kill on this one.

Proof: http://jsfiddle.net/iambriansreed/nTnhW/

Pure JavaScript:

var input_ids = ['p','k','ka','su'];

for (var i = 0, j = input_ids.length; i < j; i++) {
    var element = document.getElementById(input_ids[i]);
    alert(element.value);
}​
iambriansreed
  • 21,935
  • 6
  • 63
  • 79
  • this is perfect. how to post it to php page? $.post should be in for cycle? – Osvalda Kazlaučiūnaitė Jul 10 '12 at 18:36
  • if there is going to be 50 form elements, then Is it good way to put all in input_id array one by one????????? – Nishu Tayal Jul 10 '12 at 18:38
  • @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. – iambriansreed Jul 10 '12 at 18:46
  • 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. – ssdscott Oct 25 '14 at 23:05
0

If you want to just get your text inputs and you know the form's id:

var inputs = document.getElementById('myForm').getElementsByTagName('input');
var params = {};
for(var i=0; i < inputs.length; i++){
    var curr = inputs[i];
    if(curr.getAttribute('type')==='text')){
        params[curr.getAttribute('name')] = curr.value;
    }
}

Using jQuery to post:

$.post('myUrl',params,function(data){ console.log(data); });

Or with straight javascript: https://stackoverflow.com/a/8567146/1081941

Community
  • 1
  • 1
bokonic
  • 1,751
  • 10
  • 12