kalyanasundaram v
kalyanasundaram v

Reputation: 111

ajax response text xml to html

I have a ajax function with xml data type response. I need to assign this response as drop-down control. How can I access the values of Id and Name from the XML response?

I tried data[i].getElementsByTagName("Id")[0].childNodes[0].nodeValue; which doesn't gives me any value

$.ajax({
  url: 'POWeb.asmx/GetStates?countryId=' + thisval,

  success: function (data) {
           var x = data.getElementsByTagName("KeyValueInt");
           var html = '<select>'

           for (i= 0; i < length; i++) {
                item = data[i].getElementsByTagName("Id")[0].childNodes[0].nodeValue;
                value = data[i].getElementsByTagName("Name")[0].childNodes[0].nodeValue;
                html += '<option value=' + item + '>' + value + '</option>';
           }
           html += '</select>';
           alert(html);
 },
 error: function (XMLHttpRequest, textStatus, errorThrown) {
     //some stuff on failure
 }
});


<?xml version="1.0" encoding="utf-8"?>
<ArrayOfKeyValueInt xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    
xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://tempuri.org/">
<KeyValueInt>
  <Id>51</Id>
  <Name>Ontario</Name>
</KeyValueInt>
<KeyValueInt>
  <Id>52</Id>
  <Name>Quebec</Name>
</KeyValueInt>
<KeyValueInt>
  <Id>53</Id>
  <Name>Nova Scotia</Name>
</KeyValueInt>

Upvotes: 0

Views: 676

Answers (1)

yalight
yalight

Reputation: 308

You missed end tag </ArrayOfKeyValueInt> in your XML file! And data is not an array, it is a DOM object. The following code should be okey:

success: function(data) {
       var x = data.getElementsByTagName("KeyValueInt");
       var html = '<select>'

       for (i= 0; i < x.length; i++) {
            item = x[i].getElementsByTagName("Id")[0].childNodes[0].nodeValue;
            value = x[i].getElementsByTagName("Name")[0].childNodes[0].nodeValue;
            html += '<option value=' + item + '>' + value + '</option>';
       }
       html += '</select>';
       alert(html);
},

Upvotes: 2

Related Questions