Abdul Rahman
Abdul Rahman

Reputation: 1705

reading value from XML formatted response from jquery ajax

I am sending a request to a URL using $.get(). The response text returns with the following XML:

<?xml version="1.0" encoding="UTF-8" ?>
<myNode>
  <cmd>Requested Item</cmd>
  <myValue>this is the text i need to get with jquery</myValue>
  <res>OK</res>
</myNode>

I need to get the text inside the <myValue> and </myValue> tag:

<myValue>this is the text i need to get with jquery</myValue>

I have tried the following code inside $.get() function:

$.get(url,function(xml){
    var x, i, attnode, xmlDoc, txt;
    xmlDoc = xml.responseXML;
    x = xmlDoc.getElementsByTagName('data');
}

but there is no value in variable x.

Upvotes: 3

Views: 40

Answers (2)

Mosh Feu
Mosh Feu

Reputation: 29239

Just wrap the xml with $ (jQuery) function, then you can use .find to find the node. Something like $(xml).find('myValue').html()

Demo (In this demo I'm not using ajax but the principle is the same):

var xml = '<?xml version="1.0" encoding="UTF-8" ?>' +
    '<myNode>' + 
    '<cmd>Requested Item</cmd>' +
    '<myValue>this is the text i need to get with jquery</myValue>' +
    '<res>OK</res>' + 
    '</myNode>';

var x = $(xml).find('myValue').html();
console.log(x);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Upvotes: 2

Yusril Maulidan Raji
Yusril Maulidan Raji

Reputation: 1932

Try this:

$.get(url,function(xml){
    var x, i, attnode, xmlDoc, txt;
    xmlDoc = $.parseXML( xml.responseXML );
    var $xml = $( xmlDoc );
    var myValue= $xml.find( "myValue" );
    console.log(myValue.text())
}

Documentation: https://api.jquery.com/jQuery.parseXML/

Upvotes: 1

Related Questions