Pollster API: JSONP requests with jQuery
The Pollster API now supports JSONP to allow for cross-origin HTTP requests.
jQuery has built-in support for making AJAX calls using $.ajax()
and for returning data as JSONP, but in this case, the API requires named callbacks, and does not permit the additional parameters that are generated by the default settings for $.ajax()
.
To get a response from the API:
the callback must be named either
pollsterChart
orpollsterPoll
the timestamp parameter must be removed.
To meet these requirements, you can make your $.ajax()
call in the following way:
$.ajax({
url: 'http://elections.huffingtonpost.com/pollster/api/polls.json?callback=pollsterPoll',
dataType: 'script',
type: 'GET',
cache: true
});
This does two essential things:
it specifies the name of the callback function by appending
?callback=pollsterPoll
to the end of the url.it removes the timestamp parameter by setting
cache: true
which tells the browser to cache the response.
Finally, in order to use the data from the response, you must define a function to be run when the callback is called:
window.pollsterPoll = function(incoming_data){
console.log(incoming_data);
};
Example
Here's a simple example of what this might look like in practice:
var API_SERVER = 'http://elections.huffingtonpost.com',
API_BASE = '/pollster/api/',
API_FILE = 'polls.json',
callback = '?callback=pollsterPoll',
params = '&state=NY&topic=2012-president',
latest_data;
window.pollsterPoll = function(incoming_data){
latest_data = incoming_data;
visualize();
};
$(document).ready(function(){
$.ajax({
url: API_SERVER + API_BASE + API_FILE + callback + params,
dataType: 'script',
type: 'GET',
cache: true
});
});
function visualize(){
/* do something with the latest_data object */
}