Skip to content

Instantly share code, notes, and snippets.

@fabiovalse
Last active August 29, 2015 14:02
Show Gist options
  • Save fabiovalse/64ce9d41a4c9feacdd56 to your computer and use it in GitHub Desktop.
Save fabiovalse/64ce9d41a4c9feacdd56 to your computer and use it in GitHub Desktop.
LOD CNR MI TUTORIAL - Example 3

The aim of this gist is to show how to handle the execution of simple SPARQL query over the DBpedia SPARQL endpoint using Javascript, JQuery and AJAX.

The difference between this gist and the previous gists [1] [2] is the handling of multiple table fields.

PREFIX : <http://dbpedia.org/resource/>
PREFIX dbp: <http://dbpedia.org/ontology/>
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX dbpprop: <http://dbpedia.org/property/>
SELECT ?town ?province ?population ?area ?mayor
WHERE {
?town dbp:country :Italy;
dbp:region :Tuscany;
dbp:province ?province;
dbp:populationTotal ?population;
dbp:areaTotal ?area;
dbpprop:mayor ?mayor.
}
<!DOCTYPE html>
<html>
<head>
<meta name="description" content="Seminario LOD CNR MI - Example 3" />
<meta charset="utf-8">
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="index.js"></script>
<title>Seminario Linked Data</title>
</head>
<body>
<h1>EXAMPLE N° 3</h1>
<div><b>SPARQL QUERY:</b></div>
<div id="query" contentEditable="true">
<pre>
<code>
PREFIX : &#60;http://dbpedia.org/resource/&#62;
PREFIX dbp: &#60;http://dbpedia.org/ontology/&#62;
PREFIX rdf: &#60;http://www.w3.org/1999/02/22-rdf-syntax-ns#&#62;
PREFIX dbpprop: &#60;http://dbpedia.org/property/&#62;
SELECT ?town ?province ?population ?area ?mayor
WHERE {
?town dbp:country :Italy;
dbp:region :Tuscany;
dbp:province ?province;
dbp:populationTotal ?population;
dbp:areaTotal ?area;
dbpprop:mayor ?mayor.
}
</code>
</pre>
</div>
<div>
<input type="button" onclick="retrieveData()" value="Execute Query">
</div>
<br>
<div><b>RESULTS:</b></div><br>
<div id="output_div">
</div>
</body>
</html>
function retrieveData() {
var url = 'http://dbpedia.org/sparql?default-graph-uri=http%3A%2F%2Fdbpedia.org&query=' + encodeURIComponent($('#query').text()) + '&output=json';
$.ajax({
url: url,
dataType: "json",
success: function (data) {
handle_json(data);
},
error: function(e) {}
});
}
function handle_json(json) {
$('#output_div').text("");
$('#output_div').append("<table>");
$.each(
json['results']['bindings'],
function(index, value) {
var html = "";
html += "<tr><td>" + value['town']['value'] + "</td>";
html += "<td>" + value['province']['value'] + "</td>";
html += "<td>" + value['population']['value'] + "</td>";
html += "<td>" + value['area']['value'] + "</td>";
html += "<td>" + value['mayor']['value'] + "</td></tr>";
$('#output_div').append(html);
}
);
$('#output_div').append("</table>")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment