views:

211

answers:

1

Hi, I'm trying to create a portfolio site where my pieces reside in an XML file. I'd like to store the XML DOM in a JavaScript variable so that I can access it without making a call to the server every time a user clicks to load a new piece.

Right now I have:

$(document).ready( function() {
    xml = getXML();
});

function getXML() {
    var data = $.ajax({
     url: '_lib/xml/portfolio.xml',
     dataType: 'xml',
     success: function(data) { return data; }
    });
    return data;
}

While using Firebug, if I "console.log(data)" in the anonymous function after "success:", it logs a "Document." If I "console.log(xml)" in the "$(document).ready...", it logs an XMLHTTPRequest and I can't access the XML document's DOM.

I've tried returning "data.responseXML" but that doesn't do anything. I've also tried calling a non-anonymous function after "success:" and logging the XML there, and it still comes up as "Document" which is what I need.

It seems the problem occurs when I return the XML--it changes from "Document" to "XMLHTTPRequest."

Any help would be much appreciated. Thanks!

+2  A: 

Try this:

function getXML() {
    var XML = null;
    $.ajax({
        url:      '_lib/xml/portfolio.xml',
        dataType: 'xml',
        async:    false,
        success:  function(data) {
            XML = data;
        }
    });
    return XML;
}

I don't know what '$.ajax' returns but I've tried similar to yours and it never work. So the above code is what I settle with.

EDIT Just want to emphasize that you have to have 'async: false' in the ajax request.

Hope this helps.

NawaMan
Awesome, NawaMan--thanks a ton! Maybe "$.ajax" returns the whole XML object and "success:" returns just the responseXML? Do you know why async needs to be false?
salmonete
I really have no idea about the returns :p. `async` needs to be `false` so that the function `getXML()` will wait until ajax execution success first. (XML is assigned first). :D
NawaMan