How to parse xml webservice response using Javascript or jQuery - javascript

I want to use following xml webservice.
www.musicbrainz.org/ws/2/artist/?query=artist:michael jackson
which format is like below:
<metadata><artist-list offset="0" count="3418"><artist ext:score="100" type="Person" id="f27ec8db-af05-4f36-916e-3d57f91ecf5e"><name>Michael Jackson</name><sort-name>Jackson, Michael</sort-name><gender>male</gender><country>US</country>
I just want to parse this xml & get the gender from it .
I used following code to parse xml .
Here i get ext attribute of the artist but not working .
$.ajax({
type: 'GET',
url: 'http://www.musicbrainz.org/ws/2/artist/?query=artist:michael jackson',
dataType: 'xml',
success: function(xml){
// console.log(xml);
$(xml).find('artist-list').each(function(){
$(this).find('artist').each(function(){
var ext = $(this).attr('ext');
alert(ext);
});
});
}
});
Anybody can suggest me the example to parse xml using Javascript or jQuery.

$.ajax({
type: 'GET',
url: 'http://www.musicbrainz.org/ws/2/artist/?query=artist:michael jackson',
dataType: 'xml',
success: function(xml){
$("artist", xml).each(function(){
console.log($("gender", this).text());
});
}
});
Update:
Just checked the webservice and I saw that not every artist has a gender tag specified. In this case you can use the following:
$("artist", xml).each(function(){
var gender = $("gender", this);
if(gender.length>0)
console.log($(gender).text());
});
See JSFiddle Demo here.

Related

How to simply read html from any url via javascript and proxy?

This is my proxy.php file:
$url = urldecode($_GET['url']);
$url = 'http://' . str_replace('http://', '', $url); // Avoid accessing the file system
echo file_get_contents($url); // You should probably use cURL. The concept is the same though
and my reader.js:
$(document).ready(function () {
var url = 'http://localhost/taboo.blue-world.pl/admin/proxy.php?url=' + encodeURIComponent('http://www.blue-world.pl')
$.ajax({
url : url,
type : 'GET',
dataType : 'json'
}).done(function(data) {
console.log(data.results.result[1].category); // Do whatever you want here
});
});
But it doesnt print anything. Can you help me solve it? I am not quite good with this.
Currently your are trying to get JSON response. Change dataType to html.
dataType: 'html'
It looks like you are trying to get an HTML response as JSON.
If the content is HTML you should turn you ajax call to:
$.ajax({
url : url,
type : 'GET',
dataType : 'html'
}).done(function(data) {
console.log(data); // data contains the html as a text
});
Use either dataType: 'html' in reader.js (to get HTML data)
OR
echo(json_encode(file_get_contents($url))); in proxy.php (for JSON data)
Try jQuery.parseJSON for json format
$.ajax({
url : url,
type : 'GET',
dataType : 'json'
}).done(function(data) {
var data = jQuery.parseJSON(data);
console.log(data.results.result[1].category); // Do whatever you want here
});
});

I want to access the attribute of xml tag using javascript, how I can access it?

I am getting the XML data from link "http://weather.yahooapis.com/forecastrss?p=CHXX0008&u=unit"
Following is my javscript code :
$.ajax({
type: "GET",
url: "http://weather.yahooapis.com/forecastrss?"+"p="+zipcode+"&u=c",
dataType: "xml",
success: function(xml) {
$(xml).find('channel').each(function(){
}
} } );
Using above code I am trying to access "city" attribute of tag "yweather:location". How can I accesss? Please check the XML data using link provided.
success: function(xml) {
var loc = xml.getElementsByTagNameNS('http://xml.weather.yahoo.com/ns/rss/1.0', 'location');
var city = loc[0].getAttribute('city');
console.log(city);
}
Hope this helps you. Mark as answer if you are satisfied.

Merging Javascript AJAX requests

I have a performance problem when loading a website over the network stored on an internal server. The performance issue is down to the multiple AJAX requests made in my Javascript file constantly trying to access an XML file and then getting an Image from a XML node or a Name from an XML node.
Is there a way I can merge the AJAX requests together to reduce the amount of requests from the client device to the XML file stored on the server.
My code is as below:
function getimage(getID,XMLImageID)
{
$("#" + getID).empty();
$.ajax({
type: "GET",
url: "XML/XML.xml",
dataType: "xml",
success: function(xml){
$(xml).find(XMLImageID).each(function(){
var image = $(this).find("image[href]").attr("href");
$('#'+ getID).append($("<img"+" class="+"Timages"+" src=\"" +image+"\"/>"));
});
},
error: function() {
alert("(getImage) An error occurred while processing XML file. Reasons could be: \n The XML cant be located. \n The XML is being used by another program. \n The XML is trying to parse incompatible characters. \n The XML syntax/tags are incorrect.");
}
});
}
function getdept(getid,XMLID)
{
var scriptTag = document.scripts[document.scripts.length - 1];
var parentTag = scriptTag.parentNode;
getid = parentTag.id;
$.ajax({
type: "GET",
url: "XML/XML.xml",
dataType: "xml",
success: function(xml){
$(xml).find(XMLID).each(function(){
var dept = $(this).find('Dept').text();
var id = $(this).attr("id");
var sName = $(this).find('Name').text();
$("#"+getid).append('<div class="Team_People" onmouseover="area_hover1(this);area_hover2(this)" href="#p'+id+'">'+dept+'<br />'+sName+'</div>');
});
},
error: function() {
alert("(getHierPeopleDept)An error occurred while processing XML file. Reasons could be: \n The XML cant be located. \n The XML is being used by another program. \n The XML is trying to parse incompatible characters. \n The XML syntax/tags are incorrect.");
}
});
}
The AJAX response uses a simplified code below, I just need to merge the code above to make it more neater rather than having multiple ajax requests. Not sure if this is possible (whether adding multiple parameters would work)?
$.ajax({
type: "GET",
url: "XML/XML.xml",
dataType: "xml",
success: function(xml){
$(xml).find(XMLID).each(function(){
//Get something from XML node
});
},
});
}
If anyone could guide me in the right direction that would be much appreciated!
Thanks
Regards
AJ
Create a global XML variable and query that with your function calls...
var XML = null;
function fetchXML(){
$.ajax({
type: "GET",
url: "XML/XML.xml",
dataType: "xml",
success: function(data){
XML = data;
},
error:function(){ alert('something went wrong');})
}
function getImage(id) {
$(XML).find(id).each(){ ... };
}
funcition getDept(id) {
$(XML).find(id).each(){ ... };
}

Jquery - parse XML received from URL

I have this URL, that I supposedly should receive an XML from. So far I have this:
function GetLocationList(searchString)
{
$.ajax({
url: "http://konkurrence.rejseplanen.dk/bin/rest.exe/location?input=" + searchString,
type: "GET",
dataType: "html",
success: function(data) {
//Use received data here.
alert("test");
}
});
Tried to debug with firebug, but it doesn't go into the success method.
Though, in DreamWeaver it is able to post a simple alert, which is inside the success method.
I tried writing xml as dataType, but it doesn't work (in DreamWeaver) when I write alert(data).
But it shows an alert with the entire XML, when I write html as dataType.
How do I get the XML correctly, and how do I parse and for example get the "StopLocation" element?
Try to add an Error function as well.
See enter link description here
This will give you all the informations you need to debug your code with Firefox.
$.ajax({
url: "http://konkurrence.rejseplanen.dk/bin/rest.exe/location?input=" + searchString,
type: "GET",
dataType: "html",
success: function(data) {
//Use received data here.
alert("test");
},
error: function(jqXHR, textStatus, errorThrown ){
// debug here
}
});
you need to parse it first, and then you can search for the attributes. like this.
success: function(data) {
var xml = $.parseXML(data)
$(xml).find('StopLocation').each(function()
{
var name = $(this).attr('name');
alert(name);
}
);
this will give you the name of each StopLocation.
hope this helps, you can use the same method for all other attributes in the document also.

Parse custom XML schema with jQuery

I am getting custom schema data back from an AJAX call and I need to parse it using jQuery. Any idea how to do this?
Here's the XML:
<xsd:get_customer_summary_response xmlns:xsd="http://com/acmeco/ovm/cas/xsd">
<xsd:customer_details>
<typ:phone_number xmlns:typ="http://com/acmeco/ovm/cas/types">1.555.5553002</typ:phone_number>
<typ:timezone xsi:nil="true" xmlns:typ="http://com/acmeco/ovm/cas/types" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"/>
<typ:zipcode xmlns:typ="http://com/acmeco/ovm/cas/types">3002</typ:zipcode>
...
</xsd:customer_details>
</xsd:get_customer_summary_response>
And here's the AJAX call. I can parse normal XML with the below, but not XSD stuff.
$.ajax({
type: "GET",
url: "so.xml",
dataType: "html",
success: function(returnhtml){
$("customer_details", returnhtml).find("zipcode").each(function() {
alert($(this).text());
});
}, etc.
Any ideas?
I haven't tested this, but have you tried:
$.ajax({
type: "GET",
url: "so.xml",
dataType: "html",
success: function(returnhtml){
$(returnhtml).find("customer_details zipcode").each(function() {
alert($(this).text());
});
}, etc.
The context argument of jQuery expects a DOM element.
returnhtml will be an HTML string according to jQuery's ajax() documentation if you set the dataType as HTML. If it's an XML string, you'd need to have jQuery convert it into an element you can work with first, before using it as context.
You can use $.parseXML for it.
success: function (returnhtml) {
var parsedXML = $.parseXML(returnhtml);
$(parsedXML).find("zipcode").each(function() {
alert($(this).text());
});
}
https://jsfiddle.net/chukanov/jjt894dc/

Categories

Resources