Reputation: 7554
I im building and array where my array key is from a variable like this:
var product_id = $('#product_id').val(); //22
var art = $('#article_id').val(); //229
var stk = $('#stk').val(); //20
var elements = [];
elements [art] = stk;
console.log(elements);
This is the result
Array[229]
228:"20"
length:229
__proto__:Array[0]
As you see the result, it actually created 229 array key,
When I make a AJAX POST with that variable. It post all 229 array item to it.
option[]:
option[]:
option[]:
option[]:
option[]:
option[]:
option[]:
option[]:
option[]:
option[]:
option[]:
option[]:20
It is possible I just want to post 1 key and value.
elements[229] = 20;
Not all the unused. Thanks!
Below is my ajax call
$.ajax({
url: 'product/getprice',
type: 'post',
data: { product_id: product_id, option: element },
dataType: 'text',
beforeSend: function() {
},
complete: function() {
},
success: function(json) {
json = JSON.parse(json);
},
error: function(xhr, ajaxOptions, thrownError) {
alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
}
});
Upvotes: 1
Views: 2119
Reputation: 19007
You need an Object not an Array.
Change your elements
variable syntax to be an Object using { }
,
[ ]
stands for an array.
So the only code change required is
var elements = {};
Arrays don't have a key value type structure. Object has.
When you do elements[229]
you are actually creating array of size 229. Which is not what you want
Upvotes: 1
Reputation: 1075755
The array you're creating is a sparse array (an array with lots of missing entries). It sounds like whatever it is that you're using to serialize the array doesn't handle sparse arrays the way you want it to, instead acting as though the array weren't sparse.
So that gives you two options at least:
Change the serialization code. Since you haven't shown it, we can't help you there.
or
Use an object instead of an array:
var elements = {}; // Note {}, not []
None of the other code you've shown has to change, but it's possible your serialization code may need to change if you do this.
Upvotes: 4