0

I am just trying to fetch xml data and showing it in html page using jscript. According to this tutorial i have written a sample code which is

   <script>
     xmlDoc=loadXMLDoc("http://api.openweathermap.org/data/2.5/weather?q=London&mode=xml");
     x=xmlDoc.getElementsByTagName('city');

     for(i=0;i<x.length;i++)
         {
            att=x.item(i).attributes.getNamedItem("name");
            document.write(att.value + "<br>");
         }
   </script>

   <script > 
       function loadXMLDoc(dname)
         {
           if (window.XMLHttpRequest)
            {
               xhttp=new XMLHttpRequest();
            }
           else
            {
               xhttp=new ActiveXObject("Microsoft.XMLHTTP");
            }
         xhttp.open("GET",dname,false);
         xhttp.send();
         return xhttp.responseXML;
        }
     </script>

My output in html page should be 'London'. But its showing nothing. Or plz tell about my mistake.

demo_Ashif
  • 139
  • 2
  • 18

2 Answers2

0

I think you're running into the infamous "same-origin policy" problem

To summarize, in AJAX you can't load XML content from a remote server, application or website (meaning XML data cannot originate from any domain outside of your own domain.

There area number of ways around this problem such as the use of a server-side proxy, instead of XML use JSONp or the use of CORS to break the sandbox your client app is in when running that code (if both your user's browser and the server-stack you're requesting to supports it).

Community
  • 1
  • 1
bcmoney
  • 2,889
  • 1
  • 24
  • 30
  • 1
    CORS isn't the problem; it's an open API that allows cross origin requests. – brandonscript Jan 07 '14 at 19:54
  • yeah. its an open API. – demo_Ashif Jan 07 '14 at 19:56
  • CORS may not be the problem as mentioned, it looks like support is now there for the WeatherMap API: http://bugs.openweathermap.org/issues/152 So it could be an issue with your browser version, as @r3mus mentioned it works fine from JSFiddle for me too - FF26. – bcmoney Jan 07 '14 at 20:01
  • @remus it will be helpful if you tell about your browser and browser version where u have teseted. – demo_Ashif Jan 07 '14 at 20:04
  • demo_Ashif use the developer tools (F12) in either Chrome or FireFox, and if it fails for any reason you should see some output in the Console logs with the changes @r3mus has made. – bcmoney Jan 07 '14 at 20:11
  • Thnx guys. It is solved now. I have rearranged 'function loadXMLDoc' at top of other function and it is ok now. – demo_Ashif Jan 07 '14 at 20:22
-1

Ajax is asynchronous.

You need to read about http://www.w3schools.com/ajax/ajax_xmlhttprequest_onreadystatechange.asp

That will do the business when the reply is received

Ed Heal
  • 59,252
  • 17
  • 87
  • 127