Passing value when select box change - javascript

I got a question regarding passing the value of the select option to my XML parser. First look at my code:
HTML
<table id="ProfileList">
<tr>
<td>session</td>
<td>timestamp</td>
</tr>
</table>
<select>
<option value="none">--select user--</option>
<option value="user20">user20</option>
<option value="user30">user30</option>
<option value="user40">user40</option>
<option value="user50">user50</option>
</select>
As you can see I have a select box with 5 options were only the last four are important.
Javascript
$('select').change(function() {
var user = $(this).val();
alert($(this).val());
//Sample XML
var user20 = "<?xml version='1.0' ?><results><row><session>21</session><time>2014-02-28 21:12:12</time></row><row><session>176763</session><time>2014-03-01 14:04:35</time></row></results>";
var user30 = "<?xml version='1.0' ?><results><row><session>26</session><time>2014-02-28 21:12:12</time></row><row><session>176763</session><time>2014-03-01 14:04:35</time></row></results>";
//Parse the givn XML
var xmlDoc = $.parseXML( user );
var $xml = $(xmlDoc);
var $row = $xml.find("row");
$row.each(function(){
var session = $(this).find('session').text(),
time = $(this).find('time').text();
$("#ProfileList" ).append('<tr><td>' +session+ '</td>' + '<td>' +time+ '</td></tr>');
});
});
What I want is that the value of my select option is used as input for my XML parser. If I run this code, then I will get an error that the XML is invalid.
To clarify: If I set a fixed value then it works:
var xmlDoc = $.parseXML( user20 );
But if I want to set it variable it does not work:
var xmlDoc = $.parseXML( user );
Can anyone tell me why this is and perhaps how I could solve this?
DEMO CAN BE FOUND HERE

I would use an object containing the XML samples and access each XML by its property name of the object, see http://jsfiddle.net/3po6xgmt/ which does
$('select').change(function() {
var user = $(this).val();
alert($(this).val());
//XML samples
var samples = {
user20 : "<?xml version='1.0' ?><results><row><session>21</session><time>2014-02-28 21:12:12</time></row><row><session>176763</session><time>2014-03-01 14:04:35</time></row></results>",
user30 : "<?xml version='1.0' ?><results><row><session>26</session><time>2014-02-28 21:12:12</time></row><row><session>176763</session><time>2014-03-01 14:04:35</time></row></results>"
};
//Parse the given XML
var xmlDoc = $.parseXML( samples[user] );
var $xml = $(xmlDoc);
var $row = $xml.find("row");
$row.each(function(){
var session = $(this).find('session').text(),
time = $(this).find('time').text();
$("#ProfileList" ).append('<tr><td>' +session+ '</td>' + '<td>' +time+ '</td></tr>');
});
});

Related

jQuery - Get Content from an XML Page and save to a variable

I am trying to get the content of an XML Element into a variable:
<ContactPresence>
<ContactUri>test.com</ContactUri>
<PresenceState>offline</PresenceState>
</ContactPresence>
How can I get "PresenceState" into a variable?
With jQuery, you can use parseXML
var xml = "<ContactPresence><ContactUri>test.com</ContactUri<PresenceState>offline</PresenceState></ContactPresence>",
xmlDoc = $.parseXML( xml ),
$xml = $( xmlDoc ),
$node = $xml.find( "PresenceState" );
var presenceState = $node.text(); // Should contain offline

extract value from xml using pure javascript

i am receiving xml as a web response.
<s:Envelope xmlns:s="http://schemas.example.org/soap/envelope/">
<s:Header/>
<s:Body>
<ProductIdResponse xmlns="http://example.org/">
<Product>123</Product>
<ProductIdResponse>
</s:Body>
</s:Envelope>
I am looking to extract value from xml using pure javascript and store it in variable. there are many example in stackoverflow but all are using DOM elements and jquery.
any help would be appreciated.
have a look here: XML Parser
you load the xml into an xml document, and then access the elements the same way you would on your page's document:
//initialize your xml for testing purposes
txt='<s:Envelope xmlns:s="http://schemas.example.org/soap/envelope/">';
txt=txt+'<s:Header/>';
txt=txt+'<s:Body>';
txt=txt+'<ProductIdResponse xmlns="http://example.org/">';
txt=txt+' <Product>123</Product>';
txt=txt+'<ProductIdResponse>';
txt=txt+'</s:Body>';
txt=txt+'</s:Envelope>';
if (window.DOMParser) {
parser = new DOMParser();
xmlDoc = parser.parseFromString(txt, "text/xml");
} else // Internet Explorer
{
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = false;
xmlDoc.loadXML(txt);
}
var myProduct = xmlDoc.getElementsByTagName("Product")[0].innerHTML;
alert(myProduct);
If you dont want to parse the xml into DOM, you can alternatively retrieve the data using RegEx matching
check Here for a good RegEx tester where you can practice regex.
//initialize your xml for testing purposes
txt = '<s:Envelope xmlns:s="http://schemas.example.org/soap/envelope/">';
txt = txt + '<s:Header/>';
txt = txt + '<s:Body>';
txt = txt + '<ProductIdResponse xmlns="http://example.org/">';
txt = txt + ' <Product>123</Product>';
txt = txt + ' <Product>Product 2</Product>';
txt = txt + '<ProductIdResponse>';
txt = txt + '</s:Body>';
txt = txt + '</s:Envelope>';
var myProducts = txt.match(/<Product>(.*?)<\/Product>/g);
myProducts.forEach(function(val, id) {
myProducts[id] = myProducts[id].replace(/(<([^>]+)>)/ig, "");
});
console.log(myProducts);
alert("2nd product is: " + myProducts[1]);

Issues parsing cross domain xml with jQuery

I found a solution here on SO for retrieving cross domain xml files, however I am unable to parse the returned data. I also need to set a timeout function on this in order to keep it refreshing - it is price/voulume data.
//the remote xml
site = 'http://ec2-54-201-216-39.us-west-2.compute.amazonaws.com/testb/WebService.asmx/GetTickerFromBtcE';
var yql = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent('select * from xml where url="' + site + '"') + '&format=xml&callback=?';
$.getJSON(yql, function (data) {
var xml = $.parseXML(data.results[0]),
xmlDoc = $.parseXML( xml ),
$xml = $( xmlDoc ),
$price = $xml.find( "Currency Value");
$( "#data" ).append( $price.text() );
console.log(xml);
});
a simple fiddle is here
it appears in the console under #document, as a string, I dont know if that is correct or not. It seesm like that could be an issue as well as the tag names having spaces in them e.g. "BuyPrice Value"
Ive read several other questions here and unfortunately I don't think the back end developer will deliver in jsonp, which would alleviate a lot of this. Also, what would be the best method to get this to refresh every XX minutes? Any advice is greatly appreciated.
First, you have to deal with the fact that you have an xml document inside your xml document.
var xml = $.parseXML(data.results[0]),
xmlDoc = $.parseXML( $(xml).find("string").text() ),
Then you want to get the Currency node's Value attribute.
$xml = $( xmlDoc ),
$price = $xml.find("Currency");
$( "#data" ).append( $price.attr("Value") );
Final Result:
var xml = $.parseXML(data.results[0]),
xmlDoc = $.parseXML( $(xml).find("string").text() ),
$xml = $( xmlDoc ),
$price = $xml.find("Currency");
$( "#data" ).append( $price.attr("Value") );
http://jsfiddle.net/F52a5/1/
Two ways of refreshing it:
site = 'http://ec2-54-201-216-39.us-west-2.compute.amazonaws.com/testb/WebService.asmx/GetTickerFromBtcE';
var yql = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent('select * from xml where url="' + site + '"') + '&format=xml&callback=?';
setInterval(function(){
$.getJSON(yql, function (data) {
var xml = $.parseXML(data.results[0]),
xmlDoc = $.parseXML($(xml).find("string").text()),
$xml = $(xmlDoc),
$price = $xml.find("Currency");
$("#data").append($price.attr("Value"));
});
},30*1000);
Or, the preferred method:
site = 'http://ec2-54-201-216-39.us-west-2.compute.amazonaws.com/testb/WebService.asmx/GetTickerFromBtcE';
var yql = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent('select * from xml where url="' + site + '"') + '&format=xml&callback=?';
function getNewData() {
$.getJSON(yql, function (data) {
var xml = $.parseXML(data.results[0]),
xmlDoc = $.parseXML($(xml).find("string").text()),
$xml = $(xmlDoc),
$price = $xml.find("Currency");
$("#data").append($price.attr("Value"));
setTimeout(getNewData,30*1000);
});
}
getNewData();

How to get the nodes inner text in java script?

I have a string of XML format. As shown below:
<gt>
<st>sample1</st>
<tt>sample2</tt>
<tt>sample3</tt>
</gt>
I need to get the node value in Java script file. How can I get the value?
Use .parseXML().
var xmldom = $.parseXML('<gt><st>sample1</st><tt>sample2</tt><tt>sample3</tt></gt>');
console.log($(xmldom).find('gt *'));
This will find all nodes under <gt>.
Try this code:
var xml = "<gt><st>sample1</st><tt>sample2</tt><tt>sample3</tt></gt>",
xmlDoc = $.parseXML(xml),
$xml = $( xmlDoc ),
$st = $xml.find( "st" );
alert( $st.text() );
See the js fiddle example

How to parse XML string value using jQuery?

I am new to jquery. I am trying to parse xml string using jquery. I have found one sample:
$(function () {
$.get('data.xml', function (d) {
var data = "";
var startTag = "<table border='1' id='mainTable'><tbody><tr><td style=\"width: 120px\">Name</td><td style=\"width: 120px\">Link</td></tr>";
var endTag = "</tbody></table>";
$(d).find('url').each(function () {
var $url = $(this);
var link = $url.find('link').text();
var name = $url.find('name').text();
data += '<tr><td>' + name + '</td>';
data += '<td>' + link + '</td></tr>';
});
$("#content").html(startTag + data + endTag);
});
});
In this case, I am able to parse and fetch the values from xml file, but now what I am looking for is instead of reading file from a URL, I want to read the xml from string. Say, instead of data.xml I want to parse string which consists of well formed xml.
Does anyone have any idea about this ?
Thanks in advance
Edit :
I tried a sample code on following xml;
<?xml version="1.0" encoding="utf-8" ?>
<Urls>
<url>
<name>google</name>
<link>www.google.com</link>
</url>
<url>
<name>aspdotnetcodebook</name>
<link>http://aspdotnetcodebook.blogspot.com</link>
</url>
</Urls>
When I try this on xml file, everything works fine. But when I switched to string, it returns nothing for link attribute. I am calling it as;
$(function() {
var data = $('<?xml version="1.0" encoding="utf-8" ?><Urls><url><name>google</name><link>www.google.com</link></url><url><name>aspdotnetcodebook</name><link>http://aspdotnetcodebook.blogspot.com</link></url></Urls>');
alert(data);
doWhateverItIsYourDoing(data);
});
I am unable to diagnose why this is happening.
Just pass the string directly?
function doWhateverItIsYoureDoing(xml) {
var data = "";
var startTag = "<table border='1' id='mainTable'><tbody><tr><td style=\"width: 120px\">Name</td><td style=\"width: 120px\">Link</td></tr>";
var endTag = "</tbody></table>";
$(xml).find('url').each(function() {
var $url = $(this);
var link = $url.find('link').text();
var name = $url.find('name').text();
data += '<tr><td>' + name + '</td>';
data += '<td>' + link + '</td></tr>';
});
$("#content").html(startTag + data + endTag);
}
your .get could be rewritten as:
$.get('data.xml',doWhateverItIsYoureDoing );
and if you have xml in a string already, then
var data = "<?xml version=\"1......";
doWhateverItIsYoureDoing(data);
Just put that well-formed XML string into a jQuery object:
var xml = "<?xml version=\"1.0\"?><Dialog><Adam Emotion=\"strong\">I love you!</Adam><Eva Emotion=\"low\">I love you, too!</Eva></Dialog>";
access with
alert($(xml).find('Adam').text());
or
alert($(xml).find('Adam').attr('Emotion'));
put the the XML string into javascript variable
var xmlString = $(‘<?xml version=”1.0″?><Customers><Customer Name=”Allan Border” Age=”26″ ContactNumber=”004416165245″ Address=”Unit # 24 East London” City=”London” Country=”England”></Customer><Customer Name=”Jennifer” Age=”28″ ContactNumber=”004416165248″ Address=”Unit # 28 West London” City=”London” Country=”England”></Customer></Customers>’);
Now you can parse the XML as iterate through each of the customer node…
$(xmlString).find("Customer").each(function () {
var customerName = $(this).attr("Name");
var age = $(this).attr("Age");
var contactNumber = $(this).attr("ContactNumber");
var address = $(this).attr("Address");
var city = $(this).attr("City");
var country = $(this).attr("Country");
});
Note that to properly parse any type of XML file, you want to use the parseXML() function as in:
var xml_jquery_object = jQuery.parseXML(xml);
When you do as presented in the other answers:
var html_jquery_object = jQuery(xml);
you ask jQuery to parse HTML and not XML. The big difference is that HTML removes some tags (body, html, head...) and expects certain tags to be empty (br, hr, ...). So it is likely to break the parsing of your XML file if it somehow includes such tags.
xml can be a direct string as well, of course. The AJAX .get() function returns a string to your function anyway. (The better .ajax() function can return an XML object directly.) So you may define any XML code in that variable as in:
xml = "<?xml version='1.0'?><test>...</test>";

Categories

Resources