AJAX Client for SPARQL

The SPARQL Query Service also includes a simple AJAX client that can be used for running SELECT queries against the service and then integrating them with client-side Javascript code.

At the time of writing the client has been tested in both Firefox and Internet Explorer.

Using The Client

The main object of interest is the SparqlClient object. This mediates access to the SPARQL service and provides some hooks for integrating your own handling code.

To start with you'll need to instantiate the object:

client = new SparqlClient();

Next you'll need to configure the RDF graphs that you want to query:

graphs = new Array(); graphs[0] = 'http://www.daml.org/2003/01/periodictable/PeriodicTable.owl'; client.graphs = graphs;

You can then dispatch a query like this:

client.send( ... SPARQL Query ...);

However by default all that'll happen is you'll get an alert to say how many results were returned from the service. You need to register a callback handler with the client so that you can plug in custom processing:

function myResultsHandler{ ...do something Web 2.0 like here... } client.handleResults = myResultsHandler

If you now send() a query your custom code will be invoked instead. To get access to the results directly, use this.results which is an instance of the Results object.

The Results object holds an Array which is populated with the rows returned from the query. Each row is an associative array keyed on the variable in the SELECT clause of your query.

You can also register a callback function if the client encounters an error. In this case simply register a function like this:

client.handleError = function(code) { alert('Received HTTP error code ' + code ); }

A Complete Example

The following example shows a query that listed the elements of the periodical table. The code assumes that there is a div element in the document with an id of results. The tabular results are inserted within this element.

client = new SparqlClient();
graphs = new Array();
graphs[0] = 'http://www.daml.org/2003/01/periodictable/PeriodicTable.owl';
client.graphs = graphs;

function displayResults()
   div = document.getElementById('results');
   div.innerHTML = '';

   table = document.createElement('table');
   div.appendChild( table );

   tableBody = document.createElement('tbody');

   for (i =0; i < this.results.results.length; i++)
	  row = this.results.results[i];
	  tableRow = document.createElement('tr');

	  for (var j in row)
		 tableCell = document.createElement('td');
		 tableText = document.createTextNode( row[j].value )
		 tableCell.appendChild( tableText );

		 tableRow.appendChild( tableCell );


client.handleResults = displayResults;

var query = 'PREFIX table: ' +
'<http://www.daml.org/2003/01/periodictable/PeriodicTable#> ' +
' SELECT ?name ' +
' FROM <http://www.daml.org/2003/01/periodictable/PeriodicTable.owl> ' +
' { ?element table:name ?name. }';