Combining JSON and JavaScript for embedding a SPARQL query into an HTML document

I have successfully implemented an HTML + SPARQL + JSON + JavaScript program, which can be viewed here:

Below is the code snippet for the SPARQL + JSON + JavaScript:

function retrieveData() {
  var query = "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 ?person ?b_date ?d_date ?abstract ?thumbnail WHERE { ?person rdf:type dbp:Person ; dbp:birthDate ?b_date ; dbp:deathDate ?d_date ; dbp:abstract ?abstract . OPTIONAL { ?person dbp:thumbnail ?thumbnail } FILTER ( ?b_date >= '1488-01-01'^^xsd:date && ?b_date < '1600-01-01'^^xsd:date && ?d_date < '1650-01-01'^^xsd:date ) FILTER ( langMatches(lang(?abstract), 'EN')) } ORDER BY ?person ?b_date";

  var url = 'http://dbpedia.org/sparql?default-graph-uri=http%3A%2F%2Fdbpedia.org&query=' + encodeURIComponent(query) + '&output=json';

  $.ajax({
    url: url,
    dataType: "json",
    success: function (data) {
      $('#results').show();
      $('#raw_output').text(JSON.stringify(data, null, 3));
      handle_json(data);
    },
    error: function(e) {}
  });
}

function handle_json(json) {
  $('#output_div').text("");

  $.each(
    json['results']['bindings'], function(index, value) {
      var html = "";
      name = value['person']['value'].replace("http://dbpedia.org/resource/", "");
      name = decodeURIComponent(name.replace(/_/g, " "));
      html += "<div><h3><b>" + name + ":</b> (" + value['b_date']['value'] + " - " + value['d_date']['value'] + ")</h3></div>";

      if (value['thumbnail'] != null)
        html += "<div class='inline thumb'><img style='width: 200px' src='" + value['thumbnail']['value'].replace("200px", "150px") + "'/></div>";
      else
        html += "<div class='inline thumb'><img src=''/></div>";

      html += "<div class='inline abstract'>" + value['abstract']['value'] + "</div><div class='clear'></div><br>";

      $('#output_div').append(html);
    }
  );
}
... (remaining content not shown to keep this response concise and focused on the key points)

Answer №1

The issue lies in the presence of unescaped quotes within the second query, causing the Javascript engine to detect a syntax error (an unexpected identifier). The problematic section is as follows:

var query = "…FILTER ( regex(?name, "Calzone" )) FILTER ( langMatches(lang(?abstract), "EN"))} ORDER BY ?food";

If you observe the syntax highlighting, you'll notice that the string terminates just before "Calzone". My discovery was made by examining the Javascript console in Google Chrome while loading your second example page:

To rectify this issue, you can make the following adjustment:

var query = "…FILTER ( regex(?name, 'Calzone' )) FILTER ( langMatches(lang(?abstract), 'EN'))} ORDER BY ?food";

Upon implementing this fix, you should receive the expected results:

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using httpRequest to handle binary data in JavaScript

Having trouble deciphering the response of an http request that is a binary datastream representing a jpeg image, despite numerous attempts. Edit: Including the full code snippet below: xmlhttp = false; /*@cc_on@*/ /*@if (@_jscript_versio ...

Determining the live total number of Protovis Sparkbar instances

I am currently working on a project where I need to show the ratings and corresponding dates (in string format) from a JSON file in tipsy tooltips. The data consists of a list of dates and ratings. For example: var data = [{"dates":["2010-07-01","2010-07 ...

Tips for updating state and rendering in a function component in React Native:

I am attempting to update the state before rendering the component in a function component. While I have found suggestions to use the useEffect hook for this purpose, I am finding the information on the React official site somewhat perplexing. The docume ...

Watching a specific property amongst various objects using VueJS deep watcher

Issue at Hand In my scenario, I have an array named "products" that consists of multiple objects. Each object within the product array includes a property called "price". My goal is to monitor any changes in this particular property for each product. This ...

AngularJS promise fails to resolve when attempting to read a file using the FileReader

Can someone assist me with a function I am trying to create in my service? I want the function to use FileReader to read a small image file and return the result in a promise to my controller. The issue is that while the file reaches the service without an ...

Guide to retrieving objects in React.js

Struggling to extract a country from an online JSON file that I am currently fetching. I am attempting to streamline the process by creating a function to retrieve the country from the dataset and avoid repeating code. However, I am encountering difficulti ...

Can custom directives incorporate comprehension expressions?

Is there a way to implement comprehension expressions similar to those used in ng-options, but for grouping radio buttons or checkboxes? app.js angular .module("app", []) .controller("controller", ["$scope", function($scope){ $scope.selec ...

Jquery code failing to trigger any response

Recently, I quickly created a jQuery script to dynamically populate a paragraph element in order to easily switch between player and server interaction options. However, I am currently facing an issue where my script does not populate as expected. I have a ...

Exploring Bootstrap4: Interactive Checkboxes and Labels

My form design relies on Bootstrap, featuring a checkbox and an associated label. I aim to change the checkbox value by clicking on it and allow the label text to be edited by clicking on the label. The issue I'm facing is that both elements trigger t ...

Surfing the web with Internet Explorer means music downloads rather than streaming

My music website functions properly, however I am experiencing issues when accessing it through Internet Explorer. The internet download manager is downloading music from the site without any problems in Chrome and Firefox. Is there a way to prevent or b ...

Use the document.getElementById function in JavaScript to dynamically retrieve elements based on user input in an HTML document. This will

I am currently working towards creating a gallery using pure JavaScript. To start, I am experimenting with a model that involves two buttons - when button #1 is clicked, the string "1.jpg" appears below, and when button #2 is clicked, "2.jpg" is displayed. ...

Indexing a JSON array column in MySQL with the possibility of non-JSON data present

In my MySQL 8 database, I have a multi-tenant setup. The primary table is called entity, and each tenant can configure additional fields such as field1, field2, and so on. These fields can be text fields, booleans, JSON arrays, and more. The JSON array con ...

Utilizing various colors for tooltipFontColor in Chart.js

I'm trying to customize the font color for tooltip labels in Chart.js, but I want to set different colors based on certain conditions. Specifically, I want the label color to be white by default, but change to red if a condition is met. I've look ...

Utilizing NGINX as a reverse proxy for secure communication with Node.js

I'm currently running an NGINX server setup as a reverse-proxy server for a node application. I am now trying to enable HTTPS, but every time I attempt to access the site via HTTPS, I encounter a "502: Bad Gateway" error. server { listen 80; ...

I encountered a permission denied error when trying to enter DEBUG=app ./bin/www in Node.js

After renaming 'my-application' to just 'app', I encountered an issue when running the DEBUG command in the terminal: I used DEBUG=app ./bin/www Originally, it was named 'my-application' as created by express. However, after ...

How can I implement a pause in my JavaScript code?

Below is a snippet of code that I am using in my project: $.ajax({ url: $form.attr('action'), dataType: 'json', type: 'POST', data: $form.serializeArray(), success: function (json, textStatus, XMLHttpRequest) { ...

Issue with array doesn't update when switching positions of elements

I encountered a strange issue while working on my visualizer for sorting algorithms. Everything was going smoothly until I reached the Selection Sort algorithm. The problem lies in the fact that the i value doesn't seem to change during each pass, cau ...

React code is displaying as plain text and the components are not being rendered properly

My latest creation is a component named "componentRepeater" with the main purpose of displaying multiple instances of child components. The props within the "componentRepeater" include properties for the child components, the number of repeats for the chil ...

Connecting MySQL to HTML: Step-by-step guide

I am currently working on building a website through coding in HTML using gedit. My goal is to have a login or registration feature on the homepage, which will then direct users to their own personalized page on the site. On this page, they should be abl ...

Running a function exclusively within a single div using Angular 2

I am currently using *ngFor to group items, and it's functioning correctly. However, I am having trouble displaying the "listofGroup" in the view even though it works in the console. Specifically, I need to run a function within a specific div in Angu ...