Question

The code below doesn't work. Trying to search weather locations. When I search nothing happens.

<input type="text" id="query" /><button>search</button><br />
<div id="results">

</div>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
var url='http://autocomplete.wunderground.com/aq?format=JSON&query=';
var query;
    $('button').click(function(){
        query=$("#query").val();
        $.getJSON(url+query,function(json){
            $.each(json.results,function(i,location){
               $("#results").append('<p>'+location.name+'</p>');
            });
        });
    });
});
</script>

FYI I am very inexperienced at coding (copied script from another website)

Was it helpful?

Solution

If you want to make cross domain request, you have to that with JSONP, and you should append callback function for JSONP request as mentioned here in wunderground.com, try this.

$(document).ready(function() {
    var url = 'http://autocomplete.wunderground.com/aq?format=JSON&query=';
    var query;
    $('button').click(function() {
        query = $("#query").val();
        $.getJSON(url + query + '&cb=callbackfunc', function(json) {
            $.each(json.results, function(i, location) {
                $("#results").append('<p>' + location.name + '</p>');
            });
        });
    });
});​

UPDATE:

At first you should learn what is JSONP.

cb parameter is for JSONP callback function in wunderground API as you can see here in documentation.

If you still doesn't understand why you need to use jsonp callback function,

open these two links, and you will see what is the differences between them.

without cb paramater

with cb paramater

OTHER TIPS

You can't pull data from remote sites using JavaScript for security reasons (see the same origin policy).

Work arounds involve CORS (limited browser support, not supported by that service), JSON-P (not obviously supported by that service) and using a proxy on your own server.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top