Using variable as attribute name when making $.post

Asked

Viewed 182 times

2

How do jQuery consider the NomeCampo as variable and not field?

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

$.post(FormAction, {"NomeCampo":ValorCampo},
    function(data){
        alert(data);
    }
);

1 answer

4


You are creating the object in the format JSON, that does not support variables as attribute name.

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

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

payload[NomeCampo] = ValorCampo;

$.post(FormAction, payload,
    function(data){
        alert(data);
    }
);
  • Our man, thank you very much, worked here.

  • 1

    That’s right, but it’s not about JSON, it’s about the literal object notation.

  • @bfavaretto, now I understood what you said, did not know that there was a distinction between JSON format and literal (I thought both were JSON), very good your finding.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.