tags:

views:

35

answers:

4

Hi,

I need to obtain postdata from a form and send it via ajax .
The code is given below :

var $fields = $('#myform :input').serializeArray();
var values = {} 
jQuery.each($fields, function(i, field)
{

                   values[field.name]  = field.value

 });
 myJson = JSON.stringify(values);

Now, instead of values[field.name] I want id of the element to be key of postadata to be sent . I have tried values[$(this).attr('id')] = field.value but, It is not working . Any help will be valuable

+1  A: 

insted of this

var $fields = $('#myform :input').serializeArray();

do this

var $fields = $('#myform :input').map(function(){
   return {'id': this.id, 'value': this.value}
}).get();

and be careful with the $ on $fields variable.

Reigel
A: 

also you could do this

var values = {} 
$('#myform :input').each(index){
   values[$(this).attr('name')]=$(this).attr('id')
}
 myJson = JSON.stringify(values);
Christian Smorra
A: 

Don't serialize the Array. I'd guess you delete the properties of the dom-elements that way.

Try using instead:

var values = new Array(); 

//this way you'll get an array of DOM-elements with all their properties
jQuery('#myform :input').each(function(){
    $this = jQuery(this); //I do this to make the later code more readable, can be omitted

    values[$this.attr('id')] = $this.val();
});
stefan
A: 

You can use the following:

    var values = {};
    $("#myform :input").each(function(i, field) {
          values[field.id] = field.value;

    });

    var str = (JSON.stringify(values));
naikus