0

I want to retrieve an XML from a URL and store it in a variable xmlDoc.

I have the following:

if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
                xmlhttp=new XMLHttpRequest();
            } else {// code for IE6, IE5
                xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
            }

            xmlhttp.open("GET","localhost:8080/rest/xml",false);
            xmlhttp.send();
            xmlDoc=xmlhttp.responseXML; 

But I am not getting the XML file, is there something I need to add?

2
  • 1
    You should probably look at some examples, ajax requests are async, so you have to listen for the onreadystate event to capture the response Commented Jan 15, 2014 at 17:42
  • Here's an example. Commented Jan 15, 2014 at 17:42

2 Answers 2

2

The open method is passing false as the last parameter, making this a synchronous request. The OP's original code is correct, except for one thing: the URL.

xmlhttp.open("GET","http://localhost:8080/rest/xml",false);

Or if you want to make the URL agnostic to the protocol of the current page:

xmlhttp.open("GET","//localhost:8080/rest/xml",false);
Sign up to request clarification or add additional context in comments.

5 Comments

Hi Greg, i was testing it on local. Now I am testing it with a URL a user uploaded earlier. (cdn.florianbussmann.de/stackoverflow/21140602_catalog.xml). I added the "//" infront of it. It still didnt work. It works fine locally, as in I saved the XML file into my folder, and just called it by the name "21140602_catalog.xml"
You might be butting your head against the Same Domain Policy. You can only make AJAX requests to URLs in the same domain that the current web page is in. That could be why it works locally but not with the other URL.
Ok I see, so if my code is uploaded onto the same domain as the .XML file, then it will be able to access it?
I found this: anyorigin.com you think I can use this? but it is in JSON?
@Jenny: That is correct. If your HTML page is served from the same domain name as the XML file, the AJAX request should work.
0

before sending, attach a callback like this.

  xmlhttp.onreadystatechange=function()
      {
      if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
        xmlDoc=xmlhttp.responseText;
        }else if (xmlhttp.readyState==4 && xmlhttp.status != 200)
        {
         alert("error-" + xmlhttp.responseText);
        }
      }

3 Comments

Why do you want to use Synchronous ?? why not async ?
So change it to xhr.open(); then add the code you posted before Send()?
I meant xmlhttp.open("GET","localhost:8080/rest/xml",true); .. read the above answer too, may be the URL is wrong

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.