Search code examples
jqueryajax

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?


Solution

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