Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

Help with JavaScript to build graphs

Options
  • 29-03-2014 11:43am
    #1
    Registered Users Posts: 263 ✭✭


    I have been stuck on this problem and I know its something small but cannot get it working.

    I have two queries and I want the user to have an option of what query they want to display and what type of graph. I can get one working but not at the same time. I always get one says no data and the other displays and vice a versa.

    Maybe a another set of eyes will help?

    This is the code.
    <script type="text/javascript">
         
    		var resultArray = ['test'];
          // Define a callback function to receive the SPARQL JSON result.
          function myCallback(str) {
            // Convert result to JSON
            var jsonObj = eval('(' + str + ')');
    
            // Build up an array of results.
    		 resultArray = new Array();
    		resultArray[0] = jsonObj.head.vars;
    	for(var i = 0; i <  jsonObj.results.bindings.length; i++) {
    			resultArray[i+1] = new Array();
    			resultArray[i+1][0] = jsonObj.results.bindings[i].Name.value;
    			resultArray[i+1][1] = jsonObj.results.bindings[i].Population.value / 1000;
            } 
         }
          
         // Make the query.
        // sparqlQueryJson(query, endpoint, myCallback, false);
          
    	  
          google.load("visualization", "1", {packages:["corechart"]});
         
          function drawChart() {
    	  
    		var item = document.getElementById('selQuery').value;
    		
    		var item2 = document.getElementById('graphs').value;
    		
    		if (item == 'query1')
    		{
    		
    		function sparqlQueryJson(queryStr, endpoint, callback, isDebug) {
          var querypart = "query=" + escape(queryStr);
        
          // Get our HTTP request object.
          var xmlhttp = null;
          if(window.XMLHttpRequest) {
            xmlhttp = new XMLHttpRequest();
         } else if(window.ActiveXObject) {
           // Code for older versions of IE, like IE6 and before.
           xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
         } else {
           alert('Perhaps your browser does not support XMLHttpRequests?');
         }
        
         // Set up a POST with JSON result format.
         xmlhttp.open('POST', endpoint, true); // GET can have caching probs, so POST
         xmlhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
         xmlhttp.setRequestHeader("Accept", "application/sparql-results+json");
        
         // Set up callback to get the response asynchronously.
         xmlhttp.onreadystatechange = function() {
           if(xmlhttp.readyState == 4) {
             if(xmlhttp.status == 200) {
               // Do something with the results
               if(isDebug) alert(xmlhttp.responseText);
               callback(xmlhttp.responseText);
             } else {
               // Some kind of error occurred.
               alert("Sparql query error: " + xmlhttp.status + " "
                   + xmlhttp.responseText);
             }
           }
         };
         // Send the query to the endpoint.
         xmlhttp.send(querypart);
        
         // Done; now just wait for the callback to be called.
        };
    	var endpoint = "http://sws.ifi.uio.no/sparql/world";
          var query = "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>PREFIX owl: <http://www.w3.org/2002/07/owl#>PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>PREFIX w: <http://sws.ifi.uio.no/ont/world.owl#>PREFIX dbpo: <http://dbpedia.org/ontology/>PREFIX geo: <http://www.w3.org/2003/01/geo/wgs84_pos#>PREFIX dct: <http://purl.org/dc/terms/>PREFIX fn: <http://www.w3.org/2005/xpath-functions#>PREFIX afn: <http://jena.hpl.hp.com/ARQ/function#>PREFIX npdv: <http://sws.ifi.uio.no/vocab/npd#>PREFIX npdv2: <http://sws.ifi.uio.no/vocab/npd-v2#>PREFIX geos: <http://www.opengis.net/ont/geosparql#>SELECT * WHERE{ []  a w:Country ; w:hasName ?Name ; w:hasCountryPopulation ?Population ; } ORDER BY DESC(?Population) LIMIT 10" ;
    		
    		sparqlQueryJson(query, endpoint, myCallback, false);
    		var data = google.visualization.arrayToDataTable(resultArray);
    
            var options = {
              title: document.selectionForm.graphName.value,
              hAxis: {title: 'Note: All Values are in thousands',  titleTextStyle: {color: 'red'}}
    		 };
                if (item2 == 'bar'){
    			var chart = new google.visualization.BarChart(document.getElementById('chart_div'));
            chart.draw(data, options);}
    			else if (item2 == 'pie'){
    			var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
            chart.draw(data, options);
    			}
    			else if (item2 == 'column'){
    			var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
            chart.draw(data, options);
    			}
    			
          }
    	 else if (item == 'query2')
    		{
    		var endpoint = "http://sws.ifi.uio.no/sparql/world";
    		var query = "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>PREFIX owl: <http://www.w3.org/2002/07/owl#>PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>PREFIX w: <http://sws.ifi.uio.no/ont/world.owl#>PREFIX dbpo: <http://dbpedia.org/ontology/>PREFIX geo: <http://www.w3.org/2003/01/geo/wgs84_pos#>PREFIX dct: <http://purl.org/dc/terms/>PREFIX fn: <http://www.w3.org/2005/xpath-functions#>PREFIX afn: <http://jena.hpl.hp.com/ARQ/function#>PREFIX npdv: <http://sws.ifi.uio.no/vocab/npd#>PREFIX npdv2: <http://sws.ifi.uio.no/vocab/npd-v2#>PREFIX geos: <http://www.opengis.net/ont/geosparql#>SELECT * WHERE{ [] a w:City ; w:hasName ?Name ; w:hasCityPopulation ?Population ; } ORDER BY DESC(?Population) LIMIT 10";
    		var data = google.visualization.arrayToDataTable(resultArray);
    
            var options = {
              title: document.selectionForm.graphName.value,
              hAxis: {title: 'Note: All Values are in thousands',  titleTextStyle: {color: 'red'}}
    		  
    		  
            };
    			if (item2 == 'bar'){
    			var chart = new google.visualization.BarChart(document.getElementById('chart_div'));
            chart.draw(data, options);}
    			else if (item2 == 'pie'){
    			var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
            chart.draw(data, options);
    			}
    			else if (item2 == 'column'){
    			var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
            chart.draw(data, options);
    			}
    			
          }
    	  
    	}
        </script>
    <title> Pre Written - Easy Graphs </title>
    <h2>Welcome to our Pre-queried page for the Central Statistics Office</h2>
    <form name='selectionForm'>
    <table border=0 style= "align:center">
    	<tr>
    		<td><b>Queries</b></td>
    		<td><select  id= 'selQuery' name='query'>
    			<option value='query1'>Top ten countries by population</option>
    			<option value='query2'>Top ten most populated cities in the world</option>
    			<option value='query3'>Query 3</option>
    			<option value='query4'>Query 4</option>
    			</select>
    		</td>
    	</tr>
    
    	<tr>
    		<td><b>Graphs</b></td> 
    		<td><select  id='graphs' name='charts'>
    			<option value='pie'>Pie Chart</option>
    			<option value='bar'>Bar Chart</option>
    			<option value='column'>Column Chart</option>
    			<option value='bubble'>Bubble Chart</option>
    			</select>
    


Comments

  • Registered Users Posts: 263 ✭✭degzs


    This is a jsfiddle of the code http://jsfiddle.net/degzs/Wd8A5/


  • Registered Users Posts: 19 joe_joe


    whats 'google' here
    Do you need to include some library...


    Any specific reason for keeping
    'function sparqlQueryJson(queryStr,'

    inside and 'if' condition


  • Registered Users Posts: 19 joe_joe


    after looking into code further noticed...
    an async call and not waiting for its reponse...

    sparqlQueryJson(query, endpoint, myCallback, false);

    var data = google.visualization.arrayToDataTable(resultArray);

    Ideally you must expect 'resultArray' in callBack..


Advertisement