Reputation: 1141
I am trying to load my data from xml. Here is my code
function myFunction(){
debugger;
var url = "js/MyXml.xml";
var httpRequest = new XMLHttpRequest();
httpRequest.open('GET', url, true);
httpRequest.send();
var xmlDoc=httpRequest.responseXML;
}
Here in httpRequest i am getting status code is and httpRequest.responseXML = null
Cab you please help me what I am doing wrong.
Upvotes: 1
Views: 47
Reputation: 6141
In your case, you have used XMLHttpRequest call, that was Asynchronous. Also, you tried to assign the return value to your variable before the actual answer arrived, whether it was reading a file or actual response from the server.
In any case, if you decide to use Async (which is preferred way), then please observe the code provided below. Also, I encourage you to do more investigation on your own, in the links provided below.
var url = "js/MyXml.xml";
var xhttp = new XMLHttpRequest();
var xmlDoc = null;
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
xmlDoc = httpRequest.responseXML;
}
};
xhttp.open("GET", url, true);
xhttp.send();
In addition to, you could also a fetch, which should be available in your javascript environment as well. According to MDN, this is still experimental technology, but it will provide beneficial knowledge.
And lastly, for the task at hand you could use a library, that is designed to make this task easier then native XMLHttpRequest. One of them is a jQuery. It could be easier to use it.
You can find more information here. Also easy to follow SO question.
Upvotes: 3
Reputation: 992
Change it to that:
httpRequest.open('GET', url, false);
With the true parameter you're setting the request to be asynchronous.
Which means that you reading the response before the request finished executing.
Setting the last parameter to false will set the request to be synchronous so it will block your web page until the request finishes.
A proper way of doing it is creating an event on when the asynchronous request finishes.
Here is an example:
function myFunction() {
debugger;
var url = "js/MyXml.xml";
var httpRequest = new XMLHttpRequest();
httpRequest.open('GET', url, true);
httpRequest.onload = function(oEvent) {
var xmlDoc = httpRequest.responseXML;
//Continue code here
}
httpRequest.send();
}
Upvotes: 1