Abdul Rahman Abdul Rahman - 5 days ago 5
Ajax Question

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
.

Answer

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>