0

I am trying to get data from an XML file that's in the same directory as the HTML file, but no data seem to be returned (and I'm not sure how to render the data later). Here is the script (along with a sample record from the XML file I am trying to parse). Thanks for any help!

   function getFromAndDoThis(r, callback, opt="") {

    var okay = true;

    var xhr = new XMLHttpRequest();

    if (xhr) {  
        xhr.addEventListener("readystatechange", function() {callback(opt);}, false);
        xhr.open("GET", r, true);
        xhr.send(null);
    }
    else {
        okay = false;
    }

    return okay;

}

/* callback function */

function displayCurriculum(which) {

    var data = null;
    var chapters, docroot;

    data = extractXMLData(xhr);

    if (data) {

        chapters = data.getElementsByTagName("Chapter");
        docroot = document.getElementsById("contentarea")[0];

        var i = 0;

        /* put each chapter and synopsis (if any) in nodes, and put these nodes in the DOM */       

        for (i=0; i < chapters.length; i++) {

            var chapter = chapters[i];
            var synopsis = chapter.firstChild;

            var div = document.createElement("div");

            var pc = document.createElement("p");
            var ps = document.createElement("p");

            div.setAttribute("id", toString(i));

            pc.innerHTML = chapter.innerHTML;
            ps.innerHTML = synopsis.innerHTML;

            /* nodes are filled. now attach them to the DOM */

            div.appendChild(pc);
            div.appendChild(ps);

            body.appendChild(div);

        } // end for

    } // end if
    else {
        alert("No data.");
    }

} 

XML record:

<?xml version="1.0"?>
<Curriculum name="algebra">
    <Chapter>
        Numbers
        <Synopsis>
            Real numbers, the number line, arithmetic, factoring, decimals, exponents, radicals, and complex numbers.
        </Synopsis>
    </Chapter>
</Curriculum>

2 Answers 2

2

Your callback function is trying to read xhr, but the variable is out of scope. You need to pass it to the callback function as an argument.

Sign up to request clarification or add additional context in comments.

Comments

-1

I don't see you loading the XML. You can do this via Ajax

$.ajax({
    type: "GET",
    url: "yourxml.xml",
    dataType: "xml",
    success: function(displayCurriculum){
    }
});

1 Comment

The very first function in the code in the question loads the XML… and this question isn't tagged jquery so a jquery answer isn't appropriate.

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.