Mandi
Mandi

Reputation: 175

Using JavaScript to get information from BigQuery

I am new to JavaScript and Google BigQuery, so please forgive my ignorance. I am trying to write a javascript to collect data from one of the public databases on BigQuery. I found an answer to this at Obtaining BigQuery data from JavaScript code (the code for which I have pasted below) but when I saved the file as .html, replaced the client id and project number with mine, and tried to run it, I get the Authorize button and the page title. I click the Authorize button, and it disappears, but no query is run. Is there something else I was supposed to replace or is there something else I need to make this work? I saved the file as a .html, perhaps I should have saved it with a different extension?

I tried all three ways of creating a client id in the Google developers console and all gave me the same behavior.

I'm sure its just something silly that I am forgetting, but any advice would be greatly appreciated.

Here is the code given by Ryan Boyd, which I am unable to get working properly(which is surely my fault):

<html>
<head>
<script src="https://apis.google.com/js/client.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
  google.load('visualization', '1', {packages: ['geochart']});
</script>
<script>
  // UPDATE TO USE YOUR PROJECT ID AND CLIENT ID
  var project_id = '605902584318';
  var client_id = '605902584318.apps.googleusercontent.com';

  var config = {
    'client_id': client_id,
    'scope': 'https://www.googleapis.com/auth/bigquery'
  };

  function runQuery() {
   var request = gapi.client.bigquery.jobs.query({
      'projectId': project_id,
      'timeoutMs': '30000',
      'query': 'SELECT state, AVG(mother_age) AS theav FROM [publicdata:samples.natality] WHERE year=2000 AND ever_born=1 GROUP BY state ORDER BY theav DESC;'
    });
    request.execute(function(response) {     
        console.log(response);
        var stateValues = [["State", "Age"]];
        $.each(response.result.rows, function(i, item) {
          var state = item.f[0].v;
          var age = parseFloat(item.f[1].v);
          var stateValue = [state, age];
          stateValues.push(stateValue);
        });  
        var data = google.visualization.arrayToDataTable(stateValues);
        var geochart = new google.visualization.GeoChart(
        document.getElementById('map'));
        geochart.draw(data, {width: 556, height: 347, resolution: "provinces", region: "US"});
    });
  }

  function auth() {
    gapi.auth.authorize(config, function() {
        gapi.client.load('bigquery', 'v2', runQuery);
        $('#client_initiated').html('BigQuery client initiated');
    });
    $('#auth_button').hide();
  }
</script>
</head>

<body>
<h2>Average Mother Age at First Birth in 2000</h2>
<button id="auth_button" onclick="auth();">Authorize</button>
<button id="query_button" style="display:none;" onclick="runQuery();">Run Query</button>
<div id="map"></div>
</body>
</html>

Update: I opened the Developer Tools in Chrome and found this error in the console:

Failed to execute 'postMessage' on 'DOMWindow': The target origin provided ('file://') does not match the recipient window's origin ('null')

.

I tried editing in my Google Developer console as per these instructions: Google API in Javascript

Still same error.

Upvotes: 1

Views: 1694

Answers (3)

Mandi
Mandi

Reputation: 175

It turns out it was a combination of things. I had the Javascript origin not configured properly, I didn't have all the scopes needed for my query, and I couldn't just open the html file in a browser, I needed to create an HTTP server.

So I changed the code to be:

<html>
<head>
  <script src="https://apis.google.com/js/client.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
  <script type="text/javascript" src="http://www.google.com/jsapi"></script>
  <script type="text/javascript">
  google.load('visualization', '1', {packages: ['geochart']});
</script>
  <script>
  // UPDATE TO USE YOUR PROJECT ID AND CLIENT ID
var project_id = 'XXXXXXXXXXXX';
var client_id = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.apps.googleusercontent.com';

var config = {
  'client_id': client_id,
  'scope': 'https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/bigquery'
};

function runQuery() {
  var request = gapi.client.bigquery.jobs.query({
    'projectId': project_id,
    'timeoutMs': '30000',
    'query': 'SELECT state, AVG(mother_age) AS theav FROM [publicdata:samples.natality] WHERE year=2000 AND ever_born=1 GROUP BY state ORDER BY theav DESC;'
  });
  request.execute(function(response) {     
    console.log(response);
    var stateValues = [["State", "Age"]];
    $.each(response.result.rows, function(i, item) {
      var state = item.f[0].v;
      var age = parseFloat(item.f[1].v);
      var stateValue = [state, age];
      stateValues.push(stateValue);
    });  
    var data = google.visualization.arrayToDataTable(stateValues);
    var geochart = new google.visualization.GeoChart(
      document.getElementById('map'));
    geochart.draw(data, {width: 556, height: 347, resolution: "provinces", region: "US"});
  });
}

function auth() {
  gapi.auth.authorize(config, function() {
    gapi.client.load('bigquery', 'v2', runQuery);
    $('#client_initiated').html('BigQuery client initiated');
  });
  $('#auth_button').hide();
}
</script>
  </head>

  <body>
  <h2>Average Mother Age at First Birth in 2000</h2>
  <button id="auth_button" onclick="auth();">Authorize</button>
  <button id="query_button" style="display:none;" onclick="runQuery();">Run Query</button>
  <div id="map"></div>
  </body>
  </html>

I fixed my Google Javascript Origins url to be http://localhost:8888/ and my Redirect uri to be http://localhost:8888/oauth2callback, opened a command prompt to run this command from the directory of my html file:

python -m SimpleHTTPServer 8888

and then went to localhost:8888 in my browser and clicked my html file there.

Thanks so much for all the feedback!

It worked perfectly! Now to change the query for my purposes!

Upvotes: 1

Felipe Hoffa
Felipe Hoffa

Reputation: 59165

Searching for the error you got, I found this page:

Google API in Javascript

Based on the error you're receiving, my guess is that you either do not have your Javascript Origin configured properly on the Google API console you got your Client ID from, and/or you are trying to run your script from the file system instead of through a web server, even one running on localhost. The Google API client, near as I've been able to tell, does not accept authorization requests from the file system or any domain that has not been configured to request authorization under the supplied Client ID. --@citizenslave

Upvotes: 1

stephenkelzer
stephenkelzer

Reputation: 1274

Looks like you may need to add:

$('#query_button').show();

to the bottom of the auth() function

like so:

function auth() {
    gapi.auth.authorize(config, function()
     {
        gapi.client.load('bigquery', 'v2', runQuery);
        $('#client_initiated').html('BigQuery client initiated');
     });
    $('#auth_button').hide();
    $('#query_button').show();
}

Upvotes: 1

Related Questions