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);
          }
2
  • I got hammered once for offering a jQuery solution where it wasn't asked for. So with that in mind check this out. Commented Jul 10, 2012 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. Commented Jul 10, 2012 at 18:49

4 Answers 4

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)
Sign up to request clarification or add additional context in comments.

3 Comments

Overkill to use jQuery for this one instance.
Even i don't suggest for using jquery for one instance only.That's why i have added javascript code here..
Your top example isn't pure JavaScript. :$
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.

1 Comment

Overkill to use jQuery for this one instance.
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);
}​

4 Comments

this is perfect. how to post it to php page? $.post should be in for cycle?
if there is going to be 50 form elements, then Is it good way to put all in input_id array one by one?????????
@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.
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.
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.