user586399
user586399

Reputation:

jQuery .post or .get pass dynamic parameters

The common way to send some request to server is

$.get('link/to/send', {
   param1: "value1",
   param2: "value2"
}, function(result) {
   // ... etc
});

Now if I want to send dynamic parameter names, can jQuery support that? (i.e. I need to write some generic code so that I can specify parameter names at runtime)

Upvotes: 3

Views: 1593

Answers (3)

Syam Mohan M P
Syam Mohan M P

Reputation: 1067

Try like this. You just create your dynamic data and call the function with your dynamic data as argument.

function sendRequest(data)
{
   $.get('link/to/send',data, function(result) { /* code here*/ });
}

Upvotes: 0

Anders
Anders

Reputation: 8577

Yes, this can be done using bracket notation. You can access object properties using square bracket ([]) just like you would access the values of an array.

In your case, the code could look like this:

//Name of the parameters
var str1 = "param1";
var str2 = "param2";

//Create an empty object
var obj = {};

//Set the values of the parameters.
obj[str1] = "value1";
obj[str2] = "value2";

//Send the GET request.
$.get('link/to/send', obj, function(result) {
   // ... etc
});

This code should be synonymous with the code in your question. It sends one parameter named param1 with value value1, and one named param2 with value value2.

Upvotes: 2

raduanastase
raduanastase

Reputation: 142

This is not jQuery dependent, it's only vanilla JavaScript.

You should do this:

var objToSend = {};
objToSend["param1"] = "value1";
objToSend["param2"] = "value2";

$.get('link/to/send', objToSend, function(result) {
    // ... etc
});

Upvotes: 4

Related Questions