1

How can I pass the variables in the parameters of ajax call. Below is the example to clarify my question:-

function updateSingleParameters(name,varName, varValue)
{
$.ajax({
    type: 'POST',
    url:name,
    data: {
        varName: varValue
    },
    success: function(data, status){
        alert("Data: " + data + "\nStatus: " + status);
    }

});

I need varName also to be treated as a variable but it is treated as a constant when I execute the script.

Kindly suggest.

Thanks in advance.

Abhishek K
  • 645
  • 1
  • 11
  • 23
  • http://stackoverflow.com/questions/2274242/using-a-variable-for-a-key-in-a-javascript-object-literal – Taysky Jun 05 '15 at 19:54

4 Answers4

4

Create an object and set the property name with the varName variable using [] syntax.

function updateSingleParameters(name,varName, varValue)
{
    var data = {};
    data[varName] = varValue;
    $.ajax({
        type: 'POST',
        url:name,
        data: data,
        success: function(data, status){
            alert("Data: " + data + "\nStatus: " + status);
        }

    });
}
Musa
  • 96,336
  • 17
  • 118
  • 137
0

The basic idea is create an object and set the key with bracket notation.

var data = {};
data[varName] = varValue;
$.ajax({
    type: 'POST',
    url:name,
    data: data,
    success: function(data, status){
        alert("Data: " + data + "\nStatus: " + status);
    }

});
epascarello
  • 204,599
  • 20
  • 195
  • 236
0

In your function, I think if you do:

   function updateSingleParameters(name,varName, varValue)
   {
     var passToAjax = varValue;
      $.ajax({
         type: 'POST',
         url:name,
         data: {
         varName: passToAjax
       },
       success: function(data, status){
       alert("Data: " + data + "\nStatus: " + status);
       }

     });

I think it would work better. But i'd need to see your HTML also to make sure that it is the problem. Also, the file where you send the ajax.

Yann Chabot
  • 4,789
  • 3
  • 39
  • 56
0

Construct the object separately.

function updateSingleParameters(name,varName, varValue)
{
var obj = {};
obj[varName] = varValue;

$.ajax({
    type: 'POST',
    url:name,
    data: obj,
    success: function(data, status){
        alert("Data: " + data + "\nStatus: " + status);
    }

});
Matt R
  • 724
  • 5
  • 14