2

I would like to fetch data from an XML file to a JS variable (I would like to use pure JS, no jQuery). But I have always get error while downloading the file:

var url = "http://www.w3schools.com/xml/note.xml";

var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", url, true);
xmlhttp.onreadystatechange = function(event){ processRequest(event,xmlhttp); };
xmlhttp.send();

function processRequest(event,xmlhttp) {
    if(xmlhttp.readyState != 4) return;
    alert("status: " +xmlhttp.status);
}

The response xml is always empty - the response status is 0.

Mark Nottingham
  • 5,546
  • 1
  • 25
  • 21
nagy.zsolt.hun
  • 6,292
  • 12
  • 56
  • 95
  • 1
    Did you checked these answers here? http://stackoverflow.com/questions/2000609/jquery-ajax-status-code-0 – ripu1581 Jan 16 '13 at 07:33

2 Answers2

1

Try local url. Your code doesn't match same origin policy

p.s. w3schools is not where you want to learn, mdn and dochub.io ;)

simoncereska
  • 3,035
  • 17
  • 24
1

Its because it violates the Same origin policy.

Do:

  1. GO to w3School website.
  2. Open developer console.
  3. Paste and run your code and you will get the result
Akhil Sekharan
  • 12,467
  • 7
  • 40
  • 57
  • Thank you for the answer. It is just strange that the browser itself can send crossDomain requests (e.g. simply opening the url), but JS is not able to do so. – nagy.zsolt.hun Jan 16 '13 at 07:47
  • _DON'T_ go to w3schools, Please, don't. [here's why](http://w3fools.com/). I'd recommend either quirksmode or MDN for good, reliable documentation... or even JavaScriptKit – Elias Van Ootegem Jan 16 '13 at 08:01