Reputation: 297
The code below passes four parameters (names) to a PHP file and it works fine. Because in my application I have more than 4 names that change with time, I tried to use a loop with array and specify "n" as the number of names that I may have. I could not find a way that made it work correctly. Can you show me how to change the working code below to include a loop where the number of names "n" is a variable.
var name1 = "a";
var name2 = "b";
var name3 = "c";
var name4 = "d";
$.ajax({
type: 'GET',
url: 'test12.php',
data: { par1: name1, par2: name2, par3: name3, par4: name4 },
});
Thnak you very much.
Upvotes: 0
Views: 173
Reputation: 33466
If all the names are globals, I would do:
var data = {}, n = 4;
for (i = 1; i <= n; i++)
data['par'+i] = window['name'+i];
$.ajax({
type: 'GET',
url: 'test12.php',
data: data // can be short-handed as "data" instead of "data: data"
});
If they are not globals, I would put the names in an array, and then loop through them this way instead:
var data = {}, names = [name1, name2, name3, name4], n = names.length;
for (i = 1; i <= n; i++)
data['par'+i] = names[i-1];
$.ajax({
type: 'GET',
url: 'test12.php',
data
});
Upvotes: 1