Arturo Arturo - 2 months ago 6
jQuery Question

JQuery: send POST request with parameter from Javascript variables

I have the following JQuery script. I want to send a POST request to the server with the parameters received in the function. Say that

key
is
userId
and
value
is
1234
. How can I do that? The code below sends
{ key: 1234 }
instead of
{ userId: 1234 }
.

function saveElement(key, value) {
$.post(SERVER_ROOT + '/dosomething', { key: value } )
.done(function( data ) {
alert('done!');
});
}

Answer

In ES5 and earlier, you have to create the object, then set the property using brackets notation:

function saveElement(key, value) {
  var params = {};
  params[key] = value;
  $.post(SERVER_ROOT + '/dosomething', params )
    .done(function( data ) {
        alert('done!');
  });
}

In ES2015 ("ES6") and later, you can use computed property notation:

// REQUIRES ES2015+ SUPPORT
function saveElement(key, value) {
  $.post(SERVER_ROOT + '/dosomething', {[key]: value} )
// -------------------------------------^---^
    .done(function( data ) {
        alert('done!');
  });
}
Comments