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

ajax, javascript, jquery

Solution

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

}

Problem

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!

Original source

Related problems