views:

32

answers:

1

Hi I have a form with different groups of checks boxes and trying to pass all the selected values into an array then pass that data into a ajax request.

$('#accessoriesOptions input').each(function(index, value){
    if($(this).attr('checked') ){
        var newItem =[];
        var obj = {};
        obj[$(this).attr('value')] = $(this).attr('name'); //I have an hash table with the key-value
        wizard.searchArray.push(obj);
    }            
})

$.ajax({
   data : wizard.searchArray
})

I get a wizard.searchArray like :

   [0] = {'acc_1' : 'vase'},
   [1] = {'acc_3' : 'ceramic'}

I need to create a key-value as I use the key to work out which part of the filtering to use.

The problem

When I do the ajax request, from firebug I see the request as :

/wizard-demo/?undefined=undefined&undefined=undefined

+2  A: 

In this case just push add the properties to the obj and use it directly, that's the pair that'll get serialized property when used as the data property, like this:

var obj = {};
$('#accessoriesOptions input').each(function(index, value){
    if(this.checked){
        obj[this.value] = this.name;
    }            
})

$.ajax({
   data : obj
});

Though this is backwards from a normal <form> submission, if that's what you want it's this instead:

obj[this.name] = this.value;

If you wanted to send the entire form, there's a much shorter/built-in .serialize() method for this:

$.ajax({
   data : $("#accessoriesForm").serialize()
});
Nick Craver
Thanks so much for the tip on serialize! Planning to use this instead!
Joe