Reputation: 7563
I'm trying to submit some data via Ajax, but one of my key names and its value must be dynamic. This is what I mean:
var ProductName = $('#Product').attr('name'); // #Product is hidden form element
var ProductID = $('#Product').val();
$.ajax({
type: 'post',
url: 'form/processor/page',
data: {
SomeElement: ItsValue,
AnotherElement: ItsValue,
ProductName: ProductID // this one must be dynamic
},
....
So essentially I want to use the value of the ProductName
variable to provide the key name, and ProductID
to provide the key's value.
How could I do this?
Upvotes: 3
Views: 4152
Reputation: 277
When programming with jQuery, simply put the variable within brackets to send the string value of the variable as the key name.
var SomeElement = 'data1';
$.ajax({
type: 'post',
url: 'form/processor/page',
data: { [SomeElement] : 'val1' },
...
});
Upvotes: 0
Reputation: 4318
var data = {
SomeElement: ItsValue,
AnotherElement: ItsValue
};
data[ProductName] = ProductID;
$.ajax({
type: 'post',
url: 'form/processor/page',
data: data,
...
});
Upvotes: 10
Reputation: 3236
Create a data variable and assign the key value pairs
var post_data = {}
data[$('#Product').attr('name')] = $('#Product').val()
data["not_dynamic_key"] = "not dynamic value"
$.ajax({
data : post_data ...
Upvotes: 3