JQuery: sends a POST request with a JavaScript variable parameter

advertisements

This question already has an answer here:

  • How do I create a dynamic key to be added to a JavaScript object variable [duplicate] 2 answers

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!');
  });
}


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!');
  });
}