volume one
volume one

Reputation: 7563

How to use a variable value as the key name in an ajax data submit?

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

Answers (3)

Stan S.
Stan S.

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

Mehdi
Mehdi

Reputation: 4318

var data = { 
    SomeElement: ItsValue,
    AnotherElement: ItsValue
};
data[ProductName] = ProductID;
$.ajax({
    type: 'post',
    url: 'form/processor/page',
    data: data,
    ...
});

Upvotes: 10

Parsa
Parsa

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

Related Questions