0

Hello I want to get xml from Google Weather

var xmlhttp;

if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp= new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }

 xmlhttp.open("GET", "http://www.google.com/ig/api?weather=london&hl=en", true);

xmlhttp.send(null);

xmlDoc=xmlhttp.responseXML;

It`s not working . Thanks

Matt Ball
  • 354,903
  • 100
  • 647
  • 710
user766182
  • 19
  • 1
  • 5
  • 1
    We see this "it's not working" problem a lot. That's just not descriptive enough. **What** is not working? **How** is it failing? – Matt Ball Jun 20 '11 at 15:48

3 Answers3

3

XMLHttpRequest is asynchronous. You need to use a callback. If you don't want to use a full-fledged library, I recommend using Quirksmode's XHR wrapper:

function callback(xhr)
{
    xmlDoc = xhr.responseXML;
    // further XML processing here
}

sendRequest('http://www.google.com/ig/api?weather=london&hl=en', callback);

If you absolutely insist on implementing this yourself:

// callback is the same as above

var xmlhttp;

if (window.XMLHttpRequest)
{
    xmlhttp = new XMLHttpRequest();
}
else
{
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}

xmlhttp.open("GET", "http://www.google.com/ig/api?weather=london&hl=en", true);

xmlhttp.onreadystatechange = function ()
{
    if (xmlhttp.readyState != 4) return;
    if (xmlhttp.status != 200 && xmlhttp.status != 304) return;
    callback(xmlhttp);
};

xmlhttp.send(null);

Edit

As @remi commented:

I think you'll get a cross domain access exception : you can't make an ajax request to an other domain than your page's. no ?

Which is (for the most part) correct. You'll need to use a server-side proxy, or whatever API that Google provides, instead of a regular XHR.

Community
  • 1
  • 1
Matt Ball
  • 354,903
  • 100
  • 647
  • 710
-1

You can't do this via javascript to to it being a cross-domain request. You'd have to do this server-side.

In PHP you'd use CURL.

What you are trying to do can't be done with Javascript.

timw4mail
  • 1,716
  • 2
  • 13
  • 16
-1

Ok here is the code :

<html>
<body>

<script type="text/javascript">

var xmlhttp;
var xmlDoc;
function callback(xhr)
{
    xmlDoc = xhr.responseXML;
    // further XML processing here
}


if (window.XMLHttpRequest)
{
    xmlhttp = new XMLHttpRequest();
}
else
{
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}

xmlhttp.open("GET", "http://www.google.com/ig/api?weather=london&hl=en", true);
xmlhttp.onreadystatechange = function ()
{
    if (xmlhttp.readyState != 4) return;
    if (xmlhttp.status != 200 && xmlhttp.status != 304) return;
    callback(xmlhttp);
};

xmlhttp.send(null);



alert(xmlDoc);

</script>

</body>
</html>

It doesn`t returns any errors but alert returns undefined.

user766182
  • 19
  • 1
  • 5