2

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

1 Answer 1

6

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

1 Comment

Thanks so much for the tip on serialize! Planning to use this instead!

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.