Dynamic attribute name in Post Jquery

Asked

Viewed 37 times

0

How can I use the type variable data as the title/name of the attribute that will be passed in POST?

The type is dynamic because it is actually the name of the column in the database.

$('body').on('click', '.setCompany', function(e){
        var type = $('.modal.in').attr('data-type')
        var id = $(this).attr('id')

        $.post("/admin/purchase_orders_groups/8",
            { ${type}: id, _method: 'PUT' }
        )
})
  • that sounds kind of weird.. on the server side you receive an object without knowing the name of the property? wouldn’t it be easier to receive a pair of "name/value"? like this var postData = { nome: type, valor: id }

  • I can do that too, it just implies more code in the backend. I’m really trying to simplify. On the server side yes, there is a Validator barring what is not feasible and accepting what is ideal.

  • I understand and really have to change the backend, but it doesn’t always simplify becomes simpler and clear to understand. In this example I gave, anyone who reads the code will know what is being sent and received

  • I fully agree, even if there is some way to make the name of the element dynamic, it would be even simpler to understand. Consider it could be { $type = id } It would be easy too

1 answer

1


So I think it solves your problem:

var type = 'AlgumaCoisa';
var id   = 'AlgumValor';

var x = { [`${type }`]: id, _method: 'PUT' };
console.log(x);

This works in the Ecmascript 6

  • Sensational, that’s exactly what I thought. But I didn’t know exactly how to look for it. Thank you very much!

  • I had seen something similar here in the code that someone did, also did not know how to look for rs

Browser other questions tagged

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