None
None

Reputation: 5670

Extract XML data from ajax result

My AJAX call is like this

$.ajax({
    url: '/services/LTLGadgetV2.aspx',
    type: 'Get',
    success: function (result) {      
        console.log( result);  }
    });

In the console I get this as a result:

enter image description here Sample XML

  <RateResults xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<PriceSheets>
  <PriceSheet type="Cost" CurrencyCode="USD" CreateDate="0001-01-01T00:00:00">
    <LaneID>9553</LaneID>
    <MaxDeficitWeight>19999</MaxDeficitWeight>
  </PriceSheet>
</PriceSheets>
<StatusCode>0</StatusCode>
<StatusMessage>Rating Process completed with no errors</StatusMessage>
<debug>
  <debug>
    <ContractName>2013  Pinnacpccle </ContractName>
  </debug>
</debug>
<PricingModel><![CDATA[<div id="PricingModelDiv" style="position:absolute;display:none;"><table id="myTable" Width = "300" style="font-family:Verdana; background:white; font-size:9" border="1"> </table></div>]]></PricingModel>
</RateResults>

Can anyone please point out how I could get the XML data inside this response so that I can make operations on it? I want to parse the output to proper XML like this

   var xmlDocNp;
    xmlDocNp = $.parseXML('<xml>' + result + '</xml>'),
     $xml = $(xmlDocNp),
    pricingModel = $xml.find('PricingModel').text();

But in order to do it, I first need to extract only XML data from above result

Note: the XML data starts from RateResults tag

Note: If i put a break-point and checked the result in chrome, it looks like this

enter image description here

Upvotes: 2

Views: 1688

Answers (2)

Regent
Regent

Reputation: 5178

Since result is already Object, not a String, there is no need to use $.parseXML():

var $xml = $(result);
var pricingModel = $xml.find('PricingModel').text();

The reason for this is that even if you don't set dataType of result data in Ajax request parameters, jQuery uses Intelligent Guess to understand what the data is. Since jQuery has correctly guessed that it is XML, it executed $.parseXML() internally and passed Object instead of String to success callback.

jQuery.ajax() docs.

Upvotes: 1

R.O.M.A.N
R.O.M.A.N

Reputation: 11

$(document).ready(function () {
$.ajax({
    type: "GET",
    url: "/services/LTLGadgetV2.aspx",
    dataType: "xml",
    success: xmlParser
   });
});

function xmlParser(xml) {
    console.log($(xml).find('PricingModel'))
}

working example: http://jsbin.com/famemidoli/1/edit?js,console,output

Upvotes: 0

Related Questions