b.hendriks
b.hendriks

Reputation: 71

Looping through xml with ajax

I'm trying to get multiple bandnames after another using an each loop but all i'm getting is the final name from the loop. can somebody tell me what i'm doing wrong.

XML structure:

<resultsPage>
  <results>
    <event type="concert">
      <performance displayName="bandname1"></performance>
      <performance displayName="bandname2"></performance>
      <performance displayName="bandname3"></performance>
    </event>
  </results>
</resultsPage>

ajax:

$.ajax({
    url: 'xml/timeline.xml',
    dataType: 'xml',
    success: function(data){
        $(data).find('resultsPage results event').each(function(){
            var type = $(this).attr('type');
            var band = $(this).find('performance artist').each(function(){
                name = $(this).attr('displayName');
            })

            $('.timeline ul').append(
                '<li>A '+type+' played by '+name+'</li>'
            );

        });
    },
    error: function(){
        $('.timeline').text('Failed to get feed');
    }
});

Upvotes: 1

Views: 2880

Answers (1)

You are overwriting the name variable in each iteration. Change to:

$(data).find('resultsPage results event').each(function(){
    var type = $(this).attr('type');
    var band = $(this).find('performance artist');
    var length = $(band).length;
    $(band).each(function(index, element){
        name += $(this).attr('displayName');
        if (index < length-1) {
           name += ", ";
        }
    });

    $('.timeline ul').append(
        '<li>A '+type+' played by '+name+'</li>'
    );

});

Upvotes: 1

Related Questions