MaxZ
MaxZ

Reputation: 793

Jquery AJAX function - how can I use a variable for JSON?

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!

Upvotes: 4

Views: 3368

Answers (3)

ezakto
ezakto

Reputation: 3194

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.

Upvotes: 0

Callan
Callan

Reputation: 475

You can set object values like this.

var obj = {};

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

//This...
var varName = 'value1'
obj[varName] = 'one';

Upvotes: 0

Aguardientico
Aguardientico

Reputation: 7779

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) {
      .
      .
      .
    }
  });

}

Upvotes: 5

Related Questions