views:

561

answers:

3

Hay guys, I'm doing some work where i have a large collection of forms. Seems these aren't 'posted' the traditional way (i.e using a submit button). I need a way to collect all the names and values of all form data when clicking a link (document.location is then used for redirects).

I want names to stay intact so that i can used a simple PHP script to work with the data.

any suggestions?

A: 

You could use something like my submit helper as a base

function submit(form) {
  var form = $(form);
  $.ajax(
    { data: $.param( form.serializeArray()),
      dataType:'script',
      type:'post',
      url: form.attr("action")});
}

instead of a 'serializeArray()' i would use 'serialize()' and instead of posting it using ajax you could do whatever you want.

Sorry, dont have more time right now, but hopefully this snippet helps you.

reto
I think the combination of $.param and form.serializeArray() is the key. not seralize :). but I'm not sure.
reto
+2  A: 

Might I suggest Serialize Form to JSON:

$.fn.serializeObject = function()
{
   var o = {};
   var a = this.serializeArray();
   $.each(a, function() {
       if (o[this.name]) {
           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;
};

and then you can do:

var formArray = $("#myform").serializeObject();
cletus
A: 

cletus's answer is the best one in terms of efficency.

This is however another working solution that does not rely on JSON:

//this is my object I will fill my array with
function myObject(name, value)
{
    this.name = name;
    this.value = value;
}

var arr = $.map(
    $('span'), function (item) {
       var $item = $(item); //no need to $(item) 2 times
       return new 
         myObject(
           $item.attr("name"),     //name field
           $item.text()            //value field
         );
    }
);

arr will be an array of myObject, each of them containing a name property and a value property.

Use your selector instead of $('span').

Alex Bagnolini