0

I want to display current weather of my city on my website using yahoo weather API and jQuery.

Here is my code.

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
    $(document).ready(function () {
        $.ajax({
            type: "GET",
            url: "http://weather.yahooapis.com/forecastrss?w=12758714",
            dataType: "xml",
            success: function (xml) {
                var title = $(xml).find('condition').attr('temp');
                $('<div> </div>').html('<p>' + title + '</p>').appendTo('#a');
            },
            error: function (data) {
                $('<div> </div>').html('<p>  Error </p>').appendTo('#a');
            }
        });
    });
</script>
</head>
<body id="a">

</body>
</html>

When I am running this code, Error is being displayed. I am new to jQuery and ajax so not able to solve this problem. When I open http://weather.yahooapis.com/forecastrss?w=12758714 to my browser and save all the content of it to an xml file, and then give the url of that xml file, my code is running perfectly. But with url, It not. Can anyone please help me with this?

Thanks you in advance

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459

2 Answers2

0

You can not make cross-domain request directly. Try different approach:

Alexey Prokhorov
  • 3,431
  • 1
  • 22
  • 25
-1

Its a cross domain issue. http://en.wikipedia.org/wiki/Same-origin_policy

The best way would be to call your back-end [PHP/JAVA/RoR...] instead of calling Yahoo weather API in the AJAX call. And then in your back-end, you may call Yahoo weather API. This adds a layer, but that seems the safest way. Moreover you can work on the received data in your back-end, if needed.

G S Bajaj
  • 84
  • 1
  • 7
  • @G S Bajaj : Is there any example of what you just said? Or can I do it this way? Call yahoo API in backend and then store all the data returned by the url in a xml file and then I call that xml file. Is it feasible? – user3363460 Feb 28 '14 at 15:29
  • @user3363460 Actually all this can be part of one flow which may be like this: [a] From Frontend ajax call to [b] In the controller function pointed by , make a call to required Yahoo API. [You may use curl, if using PHP] [c] Get the result of the Yahoo API call and send back to Frontend. No need to store unless you really want to. [d] In Frontend handle the response as if its from Yahoo. This approach will work on all browser, all version. The only thing is you have one extra call to your server. – G S Bajaj Mar 03 '14 at 03:27
  • @whoever voted negative: Can you please explain why? – G S Bajaj Jul 16 '14 at 06:04