Bibliographica API Demo

# Using the Bibliographica SPARQL API from Javascript

Enter a term and retrieve results from the Bibliographica SPARQL API using javascript.

### Results

## How this works

Here's the key piece of javascript (for full details, including snippet of jquery to bind the search form event, look at the html source of this page).

    function runQuery(term) {
      // use third party js sparql library -  see ../js/vendor/sparql.js
      var sparqler = new SPARQL.Service("http://bibliographica.org/sparql");

      // set up some prefixes -- if you are not familiar with SPARQL and prefixes
      // have a quick Google
      sparqler.setPrefix("dc", "http://purl.org/dc/terms/");
      sparqler.setPrefix("bibo", "http://purl.org/ontology/bibo/");
      sparqler.setPrefix("foaf", "http://xmlns.com/foaf/0.1/");

      // The actual SPARQL query we'll run
      var sparql = "SELECT DISTINCT ?book ?title ?name " +
      "WHERE { " +
      "    ?book a bibo:Book . " +
      "    ?book dc:title ?title . ?title bif:contains \"" + term + "\" . " +
      "    OPTIONAL { " +
      "        ?book dc:contributor ?author . ?author foaf:name ?name " +
      "    } " +
      "} GROUP BY ?book LIMIT 10";

      // Create the query
      var query = sparqler.createQuery();

      // And run it (asynchronous so we need callbacks for the json results)
      query.query(sparql, {
        // we get json back from the query
        success: function(json) {
          console.log(json);
          // get the actual results
          // we'll have items corresponding to the ?book, ?title, ?name and ?location
          var resultElement = $('#results')
          // Clear out the element
          resultElement.html('');
          // iterate through our results and add them to the result list element
          // in the page
          var results = json.results.bindings;
          for (var index in results) {
            result = results[index];
            var li = $('<li></li>');
            var text = '<strong>' + result.title.value + '</strong> by <em>' + result.name.value + '</em>';
            li.append(text);
            resultElement.append(li);
          }
        },
        failure: function() {
          alert ("*sob* something went wrong");
        }
      });
    }