tags:

views:

41

answers:

2

Hello,

in first ajax call server returns a json string that is converted to js array. I want to run an ajax call for each element of array.

For example, first ajax call returns semester 1,2,3,4. Now i want to retrieve subjects for semester 1 and show them in a table, then retrieve subjects of semester 2 and show all subjects in a table and so on...

I wrote a code but it shows all subjects in last table. Can some one help me?

$.ajax(
       {
           type: "POST",
           url: "returnSemesterNumbers",
           data: "programId="+selectedprog,
           success: function(data)
           {
                var semesters=$.parseJSON(data);
                for(x in semesters)
                {
                    semnum=semesters[x].semesterNumber;
                    alert(semnum);
                    $("#tables").append('<table id=table'+x+' style=float:left><tr><td>'+semnum+'</td></tr>');
                    $.ajax(
                           {
                               type: "POST",
                               url: "returnCourses",
                               data: "programId="+selectedprog+"&semNum="+semnum,
                               success: function(data1)
                               {
                                   var courses=$.parseJSON(data1);
                                    for(y in courses)
                                    {
                                        $("#table"+x).append('<tr><td>'+courses[y].title+'</td></tr>');
                                    }
                               }
                             });
                    $("#table"+x).append('</table>');
                    }
               }
             });
            }
            else
            {
                $("#tables").css('display','none');
            }
});
+3  A: 

The callback in your inner ajax call captures the x variable by reference.

Since all of the callbacks run after the loop, they all get the current value of x, which is the last element in the set.

You need to move the code in the loop into a separate function that takes x as a parameter.

SLaks
+1  A: 

The scope of variable x might also cause issues.

Instead of:

for(x in semesters)

try:

for(var x in semesters)

Which will declare x as a variable in the scope of your first success ajax function, rather than as a global that can be changed by any other code (including jQuery).

Gus
This will not help. (There will still only be one `x` variable)
SLaks
The OP is calling a library function which could modify the global `x` before the second ajax query returns. That it doesn't is no guarantee that it won't. By adding the `var`, this possibility is avoided.
Gus
@Gus: That is unlikely (although you are right; he should use `var`). The real problem is reuse; see my answer.
SLaks
GUS's method didn't work for me..after using that method all the data was going in first table..
mysterious