4

I want to be able to supply the JSON variable name and its value via variables, instead of hard-coding it:

data: {
  inputVar : inputVal
},

but doing it like that and defining

inputVar = 'myInputVar';

doesn't work, instead entering the POST variable name directly only works:

'myInputVar' : inputVal

In the end, what I'd like to accomplish is to create a function that allows me to just call it to make an AJAX call in the JSON format, by supplying the JSON formatted AJAX variable and value in the function call:

makeAjaxJsonCall(fileName, postVar, postVal) {
  $.ajax({
    type : 'POST',
    url : fileName,
    dataType : 'json',
    data: {
      inputVar : inputVal
    },
    success : function(data) {
      .
      .
      .
    },
    error : function(XMLHttpRequest, textStatus, errorThrown) {
      .
      .
      .
    }
  });
}

Any ideas?

PS. I really don't know too much about JavaScript programming, so please be precise with full code when replying - thanks!

MaxZ
  • 723
  • 1
  • 6
  • 10
  • use `JSON.stringify()` https://www.inkling.com/read/javascript-definitive-guide-david-flanagan-6th/core-javascript-reference/json-stringify – Dhaval Marthak Jul 02 '13 at 16:29
  • duplicate of [How to create object property from variable value in javascript?](http://stackoverflow.com/questions/2241875/how-to-create-object-property-from-variable-value-in-javascript) – Bergi Jul 02 '13 at 16:33

3 Answers3

5

Do you want something like this?:

makeAjaxJsonCall(fileName, postVar, postVal) {
  var data = {};
  data[postVar] = postVal;
  $.ajax({
    type : 'POST',
    url : fileName,
    dataType : 'json',
    data: data,
    success : function(data) {
      .
      .
      .
    },
    error : function(XMLHttpRequest, textStatus, errorThrown) {
      .
      .
      .
    }
  });

}

Aguardientico
  • 7,641
  • 1
  • 33
  • 33
0

You can set object values like this.

var obj = {};

//This is the same as...
obj.value1 = 'one';

//This...
var varName = 'value1'
obj[varName] = 'one';
Callan
  • 475
  • 3
  • 11
0

A small explanation of the last two answers:

You can define elements of an object in this way:

var myObj = {};
myObj.element = 1;
// And using a variable just like you want:
var key = 'myKey';
myObj[key] = 2;

console.log(myObj.key); // 2

So, you can build your data object first, and then pass it to the ajax hash:

// ...

var myData = {};
myData[inputVal] = 'my value';

//...

makeAjaxJsonCall(fileName, postVar, postVal) {
  $.ajax({
    type : 'POST',
    url : fileName,
    dataType : 'json',
    data: myData, // <-------------
    success : function(data) {

// ...

Hope this helps. Regards.

ezakto
  • 3,174
  • 22
  • 27