Reputation: 93
I am trying to create an Ajax call to weatherunderground. The code is:
$(".city").autocomplete({
source: function( request, response ) {
$.ajax({
// GET http://autocomplete.wunderground.com/aq?query=San%20F
url: "http://autocomplete.wunderground.com/aq?query=",
dataType: "jsonp",
data: {
featureClass: "P",
style: "full",
maxRows: 12,
name_startsWith: request.term
},
success: function( data ) {
response( $.map( data.RESULTS, function( item ) {
return {
label: item.name + item.countryName,
value: item.name
};
}));
}
});
},
minLength: 2,
select: function( event, ui ) {
log( ui.item ?
"Selected: " + ui.item.label :
"Nothing selected, input was " + this.value);
},
open: function() {
$( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
},
close: function() {
$( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
}
});
No matter how I treat the question mark following aq I get an 'Uncaught SyntaxError: Unexpected token :' error. If I encode the ? as '?' I get &? in the resulting URL. If I remove the ampersand the request functions correctly. If I use either encodeURL() on the entire string or encodeURLComponent of the ? the results are %3F which doesn't work either.
I am ready to tear my hair out, does anybody know what to do?
Upvotes: 0
Views: 402
Reputation: 93
Thanks for all the help. (I know I'm not supposed to say that but nonetheless...)
The answer was two fold: As mentioned above the callback line that needed `jsonp: 'cb',
as well as the data portion instead of:
name_startsWith: request.term
it needed:
query: request.term
I did not understand the correct syntax for the data section.
Upvotes: 0
Reputation: 123513
The error actually stems from a mismatched parameter name rather than the ?
in the url
.
The parameter at issue is the one that specifies the JSONP callback:
http://.../aq?query=San%20F&callback=jQuery111___140___&ts=12345
// ^^^^^^^^
And, jQuery's default name of callback
isn't what the API is expecting:
cb JSONP callback method name
To change the parameter, you can include jsonp: 'cb'
in the request options.
$.ajax({
url: "http://autocomplete.wunderground.com/aq?query=San%20F",
dataType: "jsonp",
jsonp: 'cb',
// ...
});
Example: http://jsfiddle.net/X2JEA/
And, the syntax error is from the response. Without a cb
parameter, the service is responding with JSON, lacking the "Padding" to make it JSONP.
{"RESULTS": ...}
// ^ syntax error
jQuery111___140___({"RESULTS": ... });
// with padding
Note that JSONP is actually JavaScript and is requested with a <script>
element. It's just taking advantage of the 2 languages' similarities in syntax. But, it needs the padding to be valid.
Upvotes: 2