Abhishek K
Abhishek K

Reputation: 673

Pass variable in parameter of ajax call

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.

Upvotes: 1

Views: 10768

Answers (4)

Matt R
Matt R

Reputation: 734

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

});

Upvotes: 0

Yann Chabot
Yann Chabot

Reputation: 4879

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.

Upvotes: 0

epascarello
epascarello

Reputation: 207547

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

});

Upvotes: 0

Musa
Musa

Reputation: 97717

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

    });
}

Upvotes: 4

Related Questions