0

I am getting an undefined value to a XmlHttpRequest, the xml file has this line in it:

<market id="1" name="test">      

I can get the id returned but not the name, which returns as undefined...

$(document).ready(function () {
  $.ajax({
    type: "GET",
    url: "some url",
    dataType: "xml",
    success: function(xml) {
      var users = xml.getElementsByTagName("market")[0];
      localStorage["NAME"] = users.name;
    }  
  })
});

Where am I going wrong?

David
  • 13,619
  • 15
  • 45
  • 51
  • 2
    Are you sure there isn't a `` somewhere before this one? Also, did you try `users.getAttribute("name")`? And just as a suggestion, when using `localStorage`, you should probably use `localStorage.setItem()` (and `.getItem()`) for handling values - mainly because it's the *defined* way of doing it, as well as making sure it works for polyfills you might use – Ian Jul 19 '14 at 17:25
  • Sigh, so simple! Thanks Ian, users.getAttribute("name") worked... – David Jul 19 '14 at 17:26
  • 2
    ps, also since you use jquery: `.attr("name")` DOC: http://api.jquery.com/attr/ – GitaarLAB Jul 19 '14 at 17:27
  • 1
    @David No problem. I'm guessing the reason is because you're trying to access it by **property** (using dot notation), but `name` isn't an accepted property for a `market` element (unless you defined it somewhere in a DTD, I believe, http://stackoverflow.com/questions/1735230/can-i-add-custom-attribute-to-html-tag). `id` is a global attribute (https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes) that can be used by all elements, so it's automatically converted into a property by the parser. – Ian Jul 19 '14 at 17:29
  • 1
    @GitaarLAB Good point, I'm not sure why I didn't think of that (somehow forgot they were using `$.ajax()`). Since they are using jQuery, that's definitely the "better" solution – Ian Jul 19 '14 at 17:32

1 Answers1

0

Wrap the returned xml in $() and use jQuery methods

Assuming market isn't the root tag you can use:

 var username = $(xml).find("market").first().attr('name');

DEMO

charlietfl
  • 170,828
  • 13
  • 121
  • 150