1

I would like to retrieve a value in a xml file and use this value in another function.

I use:

function xmlparser() {
    var xmlhttp, myvar;
    xmlhttp = new XMLHttpRequest();
    xmlhttp.open("GET", "http://www.domain.net/xmlfile.xml", true);
    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            myvar = xmlhttp.responseXML.documentElement.getElementsByTagName("date")[0].textContent;
        }
    }
    xmlhttp.send();
}

How can I use myvar in another function ? Like

function test() {
    alert(myvar);
}

Thanks

1 Answer 1

1

Like so:

function test(myvar) {
    alert(myvar);
}

function xmlparser()
{
    var xmlhttp, xml_build, xml_dashboard;
    xmlhttp=new XMLHttpRequest();
    xmlhttp.open("GET", "http://www.domain.net/xmlfile.xml", true);
    xmlhttp.onreadystatechange=function()
    {
        if (xmlhttp.readyState==4 && xmlhttp.status==200) {
            myvar=xmlhttp.responseXML.documentElement.getElementsByTagName("date")[0].textContent;
            test(myvar);
        }
    }
    xmlhttp.send();
}
Sign up to request clarification or add additional context in comments.

3 Comments

Hi Thanks for your answer. But the function 'test' in a big function doing many things. I just want to use 'myvar' in 'test' before running 'test'.
When you make an AJAX request, the xmlhttp.onreadystatechange function is run once the AJAX HTTP request returns. So, the myvar variable is only set after the AJAX call returns (which could take a non-trivial amount of time). You can not rely on it's value being set until after you set it in the xmlhttp.onreadystatechange function. The function that is relying on myvar (test) should only be run after the AJAX call returns and myvar is set. You should call test inside the AJAX callback function, otherwise all bets are off as to what myvar would be set to. I hope that makes sense.
That makes perfectly sense and helped me a lot. I made few changes in my code and it works.

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.