2

Hi I have made a button through html and I am trying to get an XML page to appear when the button is clicked. I need to do this through javascript however it doesnt seem to be working for me.

My HTML:

<input type="button" value="Shop 1" id ="one">
<input type="button" value="Shop 2" id ="two">
<input type="button" value="Put Selected Pictures in Cart" id ="three">

My JavaScript:

 function getData(filename) { env = new XMLHttpRequest(); env.open("GET",            filename); } 

 function init()
{

 document.getElementById('one').onclick = function(){ getData('shop1.xml'); }
 document.getElementById('two').onclick = function(){ getData('shop2.xml'); }
}

Any help would be appreciated. Thanks.

3
  • Please post your getData function... Commented Nov 3, 2015 at 19:57
  • function getData(filename) { env = new XMLHttpRequest(); env.open("GET", filename); } Commented Nov 3, 2015 at 20:00
  • Either you did not share all of your code, or you need to make sure to send your XMLHttpRequest. So far you are just opening the request, not actually sending it. Then you need some actual code to display the result of the request, as that seems to be missing too. Commented Nov 3, 2015 at 20:54

1 Answer 1

1

As the nature of XMLHttprequests is asynchronous, you should process the retrieved data in a callback function (or you could make it synchronous by specifying env.open("GET",url, true). Your new getData function will look like so:

function getData(url, callback) { 
  var env = new XMLHttpRequest(); 
  env.onload = function() {
    callback(env.response);
  };
  env.open("GET", url); 
}

And you could use it as follows:

var one = document.getElementById('one'),
    two = document.getElementById('two');

one.onclick = function(){
  getData('shop1.xml', function(response) { 
     /* do whatever you want with the response XML */ 
  });
}
two.onclick = function(){
  getData('shop2.xml', function(response) { 
     /* do whatever you want with the response XML */ 
  });
}

See MDN: Using XMLHttpRequest for more info. Note that this will simply get the XMLdoc as a string; if you need to walk it as an XML tree, you will need to use the DOMParser API.

Sign up to request clarification or add additional context in comments.

Comments

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.