4

I would like to parse the xml data from a remote website http://services.faa.gov/airport/status/IAD?format=xml...But I was not able to parse the xml data and I am only getting error. But I was able to parse the JSON data from the same remote website http://services.faa.gov/airport/status/IAD?format=json. The code I have used to parse the xml data is:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Aviation</title>
<script type="text/javascript" src="Scripts/jquery-1.7.2.min.js"></script>
<script type="text/javascript">
    var result;
    function xmlparser() {
        $.ajax({
            type: "GET",
            url: "http://services.faa.gov/airport/status/IAD?format=xml",
            dataType: "xml",
            success: function (xml) { 
                result = xml.city;
                document.myform.result1.value = result;
            },
            error: function (xml) {
                alert(xml.status + ' ' + xml.statusText);
            }
        });             
    }        
</script>    
</head>
<body>
<p id="details"></p>
<form name="myform">
    <input type="button" name="clickme" value="Click here to show the city name" onclick=xmlparser() />
    <input type="text" name="result1" readonly="true"/>        
</form>
</body>
</html>

I was only getting the error as 'o Error' in the alert box since I have printed the error message. Anybody please helpout to parse the xml data from the remote website. Note: I have also 'City' instead of 'city' but its not working... Thanks in advance...

anglimasS
  • 1,304
  • 2
  • 16
  • 41
prabu R
  • 2,099
  • 12
  • 32
  • 41
  • 3
    Ajax can't do cross-domain requests. You would have to use a server-side script to proxy the information – Pekka Aug 02 '12 at 13:09
  • JavaScript can do cross-domain requests, via Ajax, if the response coming back is jsonp. When it comes to xml and json then you can not do a cross domain request from JavaScript and as @Pekka commented you will need to have a server-side proxy to send the request. – JustinMichaels Aug 02 '12 at 13:16
  • @Pekka : Will u please explain me how to do it with this example??? But how come i was able to do cross domain requests in ajax using JSON data??? Thank You... – prabu R Aug 02 '12 at 13:17
  • Yeah and even jsonp is a disaster cross-browser (I literally couldn't find any way of doing it in IE6-7) IE8 was a painful disaster in itself too (using XDomainRequest). Anyway... server-side proxy yes lol – Mark Pieszak - Trilon.io Aug 02 '12 at 13:17
  • You can then use JSONP. jquery provides support for this. But I don't think it a cross-doamin issue. Prabu, can you check in the network view what the response is? – unludo Aug 02 '12 at 13:18
  • @unludo : Its just showing the error status as '0' and error text as 'Error'... – prabu R Aug 02 '12 at 13:21
  • it's a cross-domain issue. look http://jsfiddle.net/eBVyZ/. This in tdev tools under chrome: XMLHttpRequest cannot load http://services.faa.gov/airport/status/IAD?format=xml. Origin http://fiddle.jshell.net is not allowed by Access-Control-Allow-Origin. – unludo Aug 02 '12 at 13:26
  • same if you change xml with json by the way... – unludo Aug 02 '12 at 13:26
  • @DeathBedMotorcade, please read [this](http://stackoverflow.com/a/2067584/1105514) JSONP explanation. – Adi Aug 02 '12 at 13:27
  • Here it works: http://jsfiddle.net/8NxDq/ – unludo Aug 02 '12 at 13:29
  • @Adnan I'm not sure why you referenced me on this since I was the one that said this can be accomplished with jsonp and jQuery does have very nice/simple jsonp support with it's ajax function – JustinMichaels Aug 02 '12 at 13:31
  • @unludo : Its showing alert box as '200 Success' but why the data is not parsed??? – prabu R Aug 02 '12 at 13:45
  • yes it's not working. You get the response back with xml, but jquery is awaiting jsonp, so it fails. There is possibly a hack, to just treat the response as text/xml. – unludo Aug 02 '12 at 13:46
  • Is there any solution for this??? So in real time we are not able to parse xml data using ajax jquery??? – prabu R Aug 02 '12 at 13:50

2 Answers2

3

I don't believe that will work since the service is still returning xml. jsonp is expecting a n object literal as an argument to pass to the callback. I believe if you run this locally you'll realize there's no data being consumable in your success. Try this

$.ajax({
    type: "GET",
    url: "http://services.faa.gov/airport/status/IAD?format=json",
    dataType: "jsonp",
    success: function (data) {
        document.myform.result1.value = data.city;
    },
    error: function (jqXHR, textStatus, errorThrown) {
        alert(errorThrown);
    }
});

Here is the example for creating a proxy with asp.net mvc 3. I just created an action that returns a ContentResult which maps to a string but I define the content type as text/xml. This simply just makes a webrequest to the service and reads the stream in to a string to send back in the response.

[HttpGet]
public ContentResult XmlExample()
{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://services.faa.gov/airport/status/IAD?format=xml");
    string xml = null;
    using (WebResponse response = request.GetResponse())
    {
        using (var xmlStream = new StreamReader(response.GetResponseStream()))
        {
            xml = xmlStream.ReadToEnd();
        } 
    }

    return Content(xml, "text/xml");
}

Your xmlParser function will look like this:

<script type="text/javascript">
    var result;
    function xmlparser() {
        $.ajax({
            type: "GET",
            url: "XmlExample",
            dataType: "xml",
            success: function (xml) {
                result = $(xml).find("City").text();
                document.myform.result1.value = result;
            },
            error: function (xml) {
                alert(xml.status + ' ' + xml.statusText);
            }
        });             
    }        
</script> 

jQuery ajax's converts the data by using $.parseXML internally which removes the requirement for us to even call this in the success block. At that point you have a jQuery object that you can use it's default DOM functions to find the City Node.

Make sure to replace the XmlExample with the url that it maps to based on your controller.

JustinMichaels
  • 1,092
  • 7
  • 12
  • Not sure why I received a down vote since if you actually run the ajax code above you will see that data argument is the json return by the service. – JustinMichaels Aug 02 '12 at 13:39
  • Quoted from the question "_But i was able to parse the JSON data from the same remote website_". OP is already able to do that, the question is about XML. – Adi Aug 02 '12 at 13:41
  • @Adnan I guess we're splitting hairs here. You are correct in that he was asking if you could parse xml via JavaScript from a cross-domain request. I merely let him know you cannot accomplish this cross-domain unless you use jsonp and gave him a solution for the jsonp. He could create a proxy from his domain and then consume it with JavaScript by calling his proxy endpoint which in turn calls the services.faa.gov service. – JustinMichaels Aug 02 '12 at 13:43
  • @DeathBedMotorcade, OP already knows that (I refer you to the same quote in my previous comment), you haven't added anything. Saying that XML wouldn't work can be simply accomplished with a comment. See, you yourself knows that you didn't offer an answer (you edited your comment to add the proxy thing), now if that was in your answer (maybe with some PHP proxying example), I'd happily upvote it. – Adi Aug 02 '12 at 13:47
  • @prabu R I could give you a proxy example with asp.net mvc if that's what your using for your server side code. – JustinMichaels Aug 02 '12 at 13:55
3

The solution is quite simple (mentioned in Pekka's comment)

1.On your server add a file IAD_proxy.php

2.Put the following code inside it

header("Content-type: text/xml; charset=utf-8");
echo file_get_contents('http://services.faa.gov/airport/status/IAD?format=xml');

3.Change the url in your Ajax request to IAD_proxy.php.

In case you're using any other server-side language, try to implement the same idea.

Edit: Please read about Parsing XML With jQuery, here's what I've tried and it's working.

Javscript:

$.ajax({
        type: "GET",
        url: "IAD_proxy.php",
        dataType: "xml",
        success: function (xml) { 
            alert($(xml).find('City').text());
        },
        error: function (xml) {
            alert(xml.status + ' ' + xml.statusText);
        }
    });

Here I tried it with document.write($(xml).find('City').text());

enter image description here

Community
  • 1
  • 1
Adi
  • 5,089
  • 6
  • 33
  • 47
  • I have tried this...But its showing the alert box as '200 OK'...still its going inside 'error' only right??? – prabu R Aug 02 '12 at 14:12
  • @unludo, quoted from OP's comment "_Is there any solution for this???_". I'd be extremely happy to see you post a client-side solution, in that case I'd learn something new. Thank you for your input :) – Adi Aug 02 '12 at 15:06