Jared Jared - 2 months ago 6
jQuery Question

Why are my object keys undefined and the values are not

I have this simple object array being built

var myData = $('.form-group input:not(.add), .form-group select').map(function() {
return {
'id': this.id,
'value': this.value
};
}).get();


If I console.log the output I can see the keys and the values

but as soon as I try to use
myData
in an $.ajax call, it drops the keys?

e.g.

$.ajax({
url: site + form,
type: 'POST',
async: false,
data: myData,
success: function(response) {
//do stuff
}
});


This is the POST headers:

console log

Answer

When posting data your data should look like:

{
    key1: val1,
    key2: val2
}

In your case, your data looked like:

[
    {
        id: key1,
        value: val1
     },
     {
        id: key1,
        value: val1
     }
]

Here is a fix for how to build your myData variable:

var myData = {}
$('select').each(function() {
    myData[this.id] = this.value;
})

console.log(myData)
$.ajax({
    url: '',
    type: 'POST',
    async: false,
    data: myData,
    success: function(response) {
        //do stuff
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="a"><option>1</option></select>

<select id="b"><option>2</option></select>

Comments