I want to use this api that returns the place matching a zipcode
e.g. for zip 11233
http://postnummersok.se/api?q=11233
I call it with a user input value like this but the result does not parse, how can I troubleshoot, is it even getting the callback? My firebug shows no js errors.
$('#zip').live("keyup",function () {
var zip = this.value.replace(/ /g,'');
if(zip.length > 4) {
var url = 'http://postnummersok.se/api?q=' + zip;
$.getJSON(url, function(data) {
$('#result').html(data);
});
} else {
$('#result').html('to short');
}
});
I assume the document your code is in is not on
http://postnummersok.se. If it isn’t, you’re running into the Same Origin Policy, which doesn’t (normally) allow ajax requests to cross origins.If this is a publicly-available service, they probably support JSON-P, which is not subject to the SOP. jQuery also supports it, so it may be as easy as changing your code from this:
to this
More in the
$.ajaxdocs.Update: Noticed when commenting on another answer that you’re dynamically creating a query string, but not encoding the parameter. If
zipcontains any characters that have to be URL-encoded, your URL will be messed up. Whenever creating query strings, you have to useencodeURIComponent:…or just pass an object with key/value pairs to jQuery, which will serialize them correctly for you. Here’s what that would look like, modifying my ajax call above:
Update 2: I got curious, and yes, you are allowed to use this service, and yes it uses JSON-P. From http://postnummersok.se/:
…which Google translates as
However, the service is broken and returning invalid JSON-P replies. If you send it
…the response is
…where it should be
(Possibly with a
;at the end.)So I’d drop them a note about the bug if I were you.