Using variable as attribute name when doing $ .post

2

How do I make jQuery look like NomeCampo as variable and not field?

var NomeCampo = $(this).attr('name');
var ValorCampo = $(this).val();

$.post(FormAction, {"NomeCampo":ValorCampo},
    function(data){
        alert(data);
    }
);
    
asked by anonymous 22.06.2014 / 22:05

1 answer

4

You are creating the object in JSON format, which does not support variables such as attribute names.

I suggest creating the object and setting the field using the variable, like this:

var NomeCampo = $(this).attr('name');
var ValorCampo = $(this).val();
var payload = {};

payload[NomeCampo] = ValorCampo;

$.post(FormAction, payload,
    function(data){
        alert(data);
    }
);
    
22.06.2014 / 22:10