adib16
adib16

Reputation: 1697

use value of variable instead of variable in getJSON function jquery

I want to send a variable to server with getJSON function in jquery.

y = "some data";
if (con == true) {
    t = "brand";
}
else {
    t = "type";
}
$.getJSON('url', { t: y }).done(function (data) {
    alert(data);
});

in the server side i have function for each information that send with getJSON. for example when i use brand instead of t , the brand() function in the server side called and when i send type instead of t , type() function in the server side called. t variable is different in some case.for example the value of t variable in one case is equal to brand and in another case is equal to type .how i can use value of t ,instead of t in this case?

Upvotes: 0

Views: 155

Answers (1)

Tanzeel Kazi
Tanzeel Kazi

Reputation: 3827

As pointed out by @u_mulder, it would be better to have the data being sent to the server in a well defined structure, so your getJSON call would look like

$.getJSON('url', { method: t, data: y }).done(function (data) {...});

If you are bent on using the structure you have mentioned you will have to do something like

var dataObj = {};
dataObj[t] = y;

$.getJSON('url', dataObj).done(function (data) {...});

This way the value of t will be populated as a property under the dataObj object. So the dataObj value will be equivalent to { brand: "some data" } or { type: "some data" } depending on the branch that is executed.

Upvotes: 1

Related Questions