0

While making a nested Ajax call, how do I pass the index of the first loop to the second loop?

Example:

$(document).ready(function() {
    $.ajax({
        type: "GET",
        url: "url1",
        dataType: "xml",
        async: false,
        success: parseXml
    });
});

function parseXml (xml){

    $title = $(xml).find("title");
    //find every Tutorial and print the author
    $title.each(function(index)
    {
        //alert($(this).text());
        if (index != 0) {
            $("#container").append('<div id=' + index + '></div>');
            $('#' + index).text($(this).text());
            $.ajax({
                type: "GET",
                url: $(xml).find('content').eq(index).attr('src'),
                dataType: "xml",
                async: false,
                success: parseInnerXml(index3)
            });
        }
    });

}

function innerXml(xml2, index3)
{
    // is this how i get the value of index3
    // also will xml2 contain the new xml doc ..
}
Joseph Silber
  • 214,931
  • 59
  • 362
  • 292
Gaurav
  • 617
  • 2
  • 9
  • 23
  • `$title = $(xml).find("title");` needs to be `var $title = $(xml).find("title");`, otherwise you're writing to a global `$title` variable... – Peter C Sep 05 '11 at 22:10
  • A side tip: Never set an `id` of an element to a value that's **not** a proper javascript variable name. Ever. It's not only bad practice but it'll garbage the DOM namespace in some browsers. Either prefix it and parse out the prefixing later or simply set a custom attribute (preferably namespaced) and select based on that later. – mr.stobbe Oct 14 '11 at 05:43

1 Answers1

0

I agree with @alpha123 that you should make $title local to the parseXml function by using var $title instead.

I'm guessing that index3 is a typo and that you want to use index in the parseInnerXml function. So you must create a closure that captures the index value. The createParseInnerXmlCallback function will do this.

function parseXml (xml){
    function createParseInnerXmlCallback(index) {
        return function () {
            parseInnerXml(index);
        }
    }

    var $title = $(xml).find("title");

    //find every Tutorial and print the author
    $title.each(function(index)
    {
        //alert($(this).text());
        if (index != 0) {
            $("#container").append('<div id=' + index + '></div>');
            $('#' + index).text($(this).text());
            $.ajax({
                type: "GET",
                url: $(xml).find('content').eq(index).attr('src'),
                dataType: "xml",
                async: false,
                success: createParseInnerXmlCallback(index)
            });
        }
    });
}
Community
  • 1
  • 1
Paul Grime
  • 14,970
  • 4
  • 36
  • 58