0
votes

I'm using Node and MySQL for the backend and Polymer for front end, and I cannot get Polymer to render a JSON array.

Node/MySQL Code

var mysql      = require('mysql');
var connection = mysql.createConnection({
    host     : 'localhost',
    user     : 'root',
    database : 'test'
});
connection.connect();



 connection.query('SELECT * FROM ACTIVITY', function(err, rows, fields) {
  if (err) {
    console.error('error connecting: ' + err.stack);
    return;
  }
  json = JSON.stringify(rows);
  console.log(json);
});

connection.end();

Polymer Frontend

<paper-dropdown-menu label="Activity Selection">
  <iron-ajax 
    id="getActivity"
    auto
    url="scripts/dbcon.js"
    handle-as="json"
    on-response="handleResponse"
    last-response="{{ajaxResponse}}">
  </iron-ajax>
  <paper-listbox class="dropdown-content">
    <template is="dom-repeat" items="[[ajaxResponse]]">
      <paper-item><b>{{item.ACTIVITY_NAME}}</b></paper-item>
    </template>
  </paper-listbox>
</paper-dropdown-menu>

JSON Output

[{"ID":1,"ACTIVITY_NAME":"Coffee"},{"ID":2,"ACTIVITY_NAME":"Gym"},{"ID":3,"ACTIVITY_NAME":"Lunch"},{"ID":4,"ACTIVITY_NAME":"Vending Machine"},{"ID":5,"ACTIVITY_NAME":"Pool"}]

When I run this command: node dbcon.js, the output from console.log is the JSON array shown above.

For some reason, Polymer isn't recognizing the JSON array. In the Chrome DevTools console, there were no errors/outputs.

In another test scenario (which is working), I manually copied the JSON array output into a file, changed the url parameter from "scripts/dbcon.js" to "scripts/test.json", and reloaded the electron app; and Polymer was able to display the JSON content in the dropdown list.

1

1 Answers

1
votes

The <iron-ajax>.url property is intended to specify the URL target of the request. It does not execute the response as JavaScript (like a <script> tag would), which seems to be what you're expecting.

In your case, the <iron-ajax> is reading the contents of scripts/dbcon.js and attempting to parse it as JSON (because of handle-as="json"). The parsing fails, resulting in a null response value.

To fix this, you should set <iron-ajax>.url to the URL of your Node server that is providing the JSON response.