Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8913439
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 15, 20262026-06-15T04:27:54+00:00 2026-06-15T04:27:54+00:00

I am going through some very basic AJAX programming in Learning PHP, MySQL &

  • 0

I am going through some very basic AJAX programming in “Learning PHP, MySQL & JavaScript -O’Reilly”. There are a couple very basic programs with Java getting some text or a page with AJAX. I am using the W3Schools.com site to try to learn more about getting XML formatted docs with AJAX. I have two questions related to what I am learning.

When I used the code from http://www.w3schools.com/dom/dom_loadxmldoc.asp I can return an XML document with the snippet below:

function loadXMLDoc(dname)
{
if (window.XMLHttpRequest)
  {
  xhttp=new XMLHttpRequest();
  }
else
  {
  xhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xhttp.open("GET",dname,false);
xhttp.send();
return xhttp.responseXML;
}

//called this way
xmlDoc=loadXMLDoc("books.xml");

But async has to be set to false for this to work. If I set async to true, it returns null. So my first question is why must async be false for this to return the XML document?

My second question, when I try to combine some of the code from the book and some from the website, snippet follows:

<body>API Call output
<div id='output'>will be here</div>
<script>
out = ""
xmlDoc = getResponse()
users = xmlDoc.getElementsByTagName('username')
for (count = 0; count < users.length ; count++)
{
    out += "Username: " + users[count].childNodes[0].nodeValue + '<br />'
}
document.getElementById('output').innerHTML = out

function ajaxRequest()
{
    try //good browser
    {
        var request = new XMLHttpRequest()
    }
    catch(e1)
    {
        try // IE6+
        {
            request = new ActiveXObject("Msxml2.XMLHTTP")
        }
        catch(e2)
        {
            request = false
        }
    }//end catch(e1)
    return request
}

function getResponse()
{
    params = "apikey=test"
    request = new ajaxRequest()
    request.open("POST", "processapi.php", true)
    request.setRequestHeader("Content-type",
        "application/x-www-form-urlencoded")
    request.setRequestHeader("Content-length", params.length)
    request.setRequestHeader("Connection", "close")
    request.onreadystatechange = function()
    {
        if (this.readyState == 4)
        {
            if (this.status == 200)
            {
                if (this.responseXML != null)
                {
                    return this.responseXML
                }
                else alert("Ajax error: No data received")
            }
            else alert( "Ajax error: " + this.statusText)
        }
    }

    request.send(params)
}
</script>
</body>

I get an error that “TypeError: xmlDoc is undefined”. In function getResponse() with async set to true or false it doesn’t work, I get the xmlDoc is undefined error. The xmlDoc is not defined elsewhere in the first example (from w3schools.com) before being set to the return of loadXMLDoc() and that works just fine. the ajaxRequest() is out of the book, and most everything in getResponse() is out of the book, but I put it in the getResponse() function. processapi.php just echos an XML document when called from this script.

Why is async not working in the first example, and why is xmlDoc undefined in the second? Any help is greatly appreciated.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-15T04:27:56+00:00Added an answer on June 15, 2026 at 4:27 am

    The answer to both of your questions lies in the nature of asynchronousness. With async being true, this returns null:

    xhttp.open("GET",dname,false);
    xhttp.send();
    return xhttp.responseXML;
    

    …because the HTTP request hasn’t completed by the time the return statement occurs, and so xhttp.responseXML still has its default value (null). The HTTP request completes later, out of the flow of that code (asynchronously — literally, not synchronous).

    Your getResponse function never returns a value at all. The anonymous callback function you’ve assigned to onreadystatechange returns a value, but that doesn’t in any way affect the return value of getResponse.

    One of the key aspects of client-side web programming is embracing the asynchronous, event-driven nature of the environment. There are virtually no use cases for setting async to false on XHR requests. Instead, get used to using callbacks for things. For instance, your getResponse function could look like this:

    // ***CHANGE*** -----v--- Accept a callback
    function getResponse(callback)
    {
        params = "apikey=test"
        request = new ajaxRequest()
        request.open("POST", "processapi.php", true)
        request.setRequestHeader("Content-type",
            "application/x-www-form-urlencoded")
        request.setRequestHeader("Content-length", params.length)
        request.setRequestHeader("Connection", "close")
        request.onreadystatechange = function()
        {
            if (this.readyState == 4)
            {
                if (this.status == 200)
                {
                    if (this.responseXML != null)
                    {
                        // ***CHANGE*** Trigger the callback with the response
                        callback(this.responseXML);
                    }
                    else alert("Ajax error: No data received")
                }
                else alert( "Ajax error: " + this.statusText)
            }
        }
    
        request.send(params)
    }
    

    Then, instead of this:

    out = ""
    xmlDoc = getResponse()
    users = xmlDoc.getElementsByTagName('username')
    for (count = 0; count < users.length ; count++)
    {
        out += "Username: " + users[count].childNodes[0].nodeValue + '<br />'
    }
    document.getElementById('output').innerHTML = out
    

    you’d do this:

    getResponse(function(xmlDoc) {
        out = ""
        users = xmlDoc.getElementsByTagName('username')
        for (count = 0; count < users.length ; count++)
        {
            out += "Username: " + users[count].childNodes[0].nodeValue + '<br />'
        }
        document.getElementById('output').innerHTML = out
    });
    

    Note how I moved all of the code that relied on the response into a function, and then passed that function into getResponse. getResponse calls it when it has the data. Request/response, event-driven, asynchronous, whatever you want to call it, this is a key thing to take onboard early. 🙂


    Side note: Your code is falling prey to The Horror of Implicit Globals. Strongly recommend declaring all of your variables, and wrapping all of your code in a scoping function to avoid creating global symbols (the global namespace on browsers is already overcrowded).

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm going through a very basic php tutorial and am creating a calculator so
I have started to learn jQuery and am going through some very simple examples
I was going through some questions related to C programming language. And i found
Going through some of my older Delphi projects and upgrading them to D2009, as
Going through some documentation on modifying CGImageRef data, I came across a strange example
While going through some tutorials, I have encountered lines such as this: ((IDisposable)foo).Dispose(); Ignore
I am going through some code and at the beginning of the script we
I was going through some code that I downloaded off the internet ( Got
I was going through some data structures and I noticed this as a time
I've been going through some good (seeming) resources for Rails tutorials, and will dutifully

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.