user766182
user766182

Reputation: 19

Simple XMLHttpRequest (Google Weather)

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

Upvotes: 0

Views: 5155

Answers (3)

user766182
user766182

Reputation: 19

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.

Upvotes: -1

timw4mail
timw4mail

Reputation: 1776

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.

Upvotes: -1

Matt Ball
Matt Ball

Reputation: 360046

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.

Upvotes: 3

Related Questions