Back to contents PHP Python Ruby Choose a language:

So you’ve read HTML Views 101 and now you want to know a bit more about AJAX?
Well you’ve come to the right place.

JSON and JSONP

As you saw, the basic recipe for calling the ScraperWiki API using jQuery.ajax() is:

var apiurl = "https://api.scraperwiki.com/api/1.0/datastore/sqlite"; var srcname = "new_americ_foundation_drone_strikes"; var sqlselect = "select * from swdata limit 10"; $.ajax({ url: apiurl, dataType: "jsonp", data:{ name: srcname, query: sqlselect, format: "jsonlist" }, success: function(data){ alert(data); } });

Note how we’re using dataType: "jsonp" there. This is because security requirements stop our script (running in http://views.scraperwiki.com) from accessing data on a different domain (in this case http://api.scraperwiki.com) using regular Ajax. Instead, we have to use JSONP, which works around the limitation.

If, instead, you are calling to the same domain (https://views.scraperwiki.com), then a plain ajax call is fine:

var url = "https://views.scraperwiki.com/run/python_output_stuff/"; $.ajax({ url: url, success: function(data){ alert(data); });

Making lots of similar $.ajax calls in your script?

You can set the defaults for all your ajax calls at once:

var apiurl = "https://api.scraperwiki.com/api/1.0/datastore/sqlite"; $.ajaxSetup({ type: "GET", dataType: "jsonp", url: apiurl, error: function(jq, status) { alert(status); } });

Now you can call back to the data API with hardly any code.

var sqlselect = "select latlng_lat, latlng_lng, date, lowerest, higherest from swdata order by date limit 500"; var name = "new_americ_foundation_drone_strikes"; $.ajax({ data:{ name: name, query: sqlselect }, success: consumedata });

Using JSON from the ScraperWiki Datastore

Data comes back from the datastore in a single entry list like this:

[ { keys:[keys], data:[row1, row1, ...] } ]

Here’s how you could turn that list into a HTML table using jQuery:

function consumedata(tdata) { var keys = tdata[0]["keys"]; var data = tdata[0]["data"]; var tab = $("<table>"); $(window).append(tab); tab.append($("<tr><th>" + keys.join("</th><th>") + "</th></tr>")); for (var i = 0; i < data.length; i++) tab.append($('<tr><td>' + data[i].join("</td><td>") + "</td></tr>")); }