1

I am trying to run this:

function loadApp() {
    var content = getContent("content.xml");
    createMap(content);
}

function getContent(file) {
    $.ajax({
        type: "GET",
        url: file,
        dataType: "xml",
        success: parseXml
    });

    function parseXml(xml) {
        var content = [];
        $("element", xml).each(function () {
            var var1 = $(this).children("var1").text(),
            content.push(var1)
        });

        return content;
    }
}

    function createMap(content) {
        alert(content);
    }

But when I open the page the alert says my content variable is undefined. getContent() works fine and gives content a string value when I delete createMap(content); from loadApp(). It seems that createMap() is running before getContent() and that is why the variable is not defined yet, any idea why this happens and how can I solve it?

Thanks in advance.

2
  • Maybe you should show us getContent() method. Maybe it has a callback. Commented Dec 24, 2010 at 5:23
  • I guess that your getContent function does an asynchronous action (like an Ajax request)... Commented Dec 24, 2010 at 5:23

1 Answer 1

2

I'd assume that getContent() makes an asynchronous AJAX call. If so, the createMap() function is called before the response is received.

If that's the case, I'd modify getContent() function so that you can pass the createMap() function to it, and call it at the right time.

function loadApp() {
    getContent( "content.xml", createMap );
}

function getContent( file, fn ) {
    $.ajax({
        type: "GET",
        url: file,
        dataType: "xml",
        success: parseXml
    });

    function parseXml(xml) {
        var content = [];
        $("element", xml).each(function () {
            var var1 = $(this).children("var1").text(),
            content.push(var1)
        });
          // Call "fn" instead of returning "content"
        fn( content );
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks this works! but is there another way for my function to run only when the first one is finished and has returned a value?
@VerizonW: The only way would be to set the ajax request to async:false, which is typically a bad idea. Ultimately, your getContent function is going to exit long before the AJAX request returns. Because of this, any code that relies on the response from the AJAX, must wait to run until the response has been received. If createMap is in a scope accessible to getContent, you could get by without passing the function, and just calling it directly in parseXML. But calling it in loadApp() won't work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.