Search code examples
htmldata-bindingpolymerpolymer-1.0

Polymer data binding from Web API


I want to bind some data to a variable on command (by the press of a button) from a server. On the server I have a function that will return a JSON object (this has been tested, if I open the API link directly, I do get the proper JSON format). However, the variable stays undefined, no matter what I do. I have a button and a table (px-data-table is part of a framework and should be able to display JSON formatted data):

<button id="runPredictionButton">
    <i>Button text</i>
</button>
<px-data-table 
      table-data$="{{data}}"
</px-data-table>
<div class="output"></div>   

And I'm handling the button press and define the variables as follows:

  <script>
    Polymer({
      is: 'custom-view',
      properties: {
        data: {
          type: Object,
          notify: true
        }
      },
    ready: function() {
      var self = this;
      this.$.runPredictionButton.addEventListener('click', function() {
          filerootdiv.querySelector('.output').innerHTML = 'Is here';    
          var xhr = new XMLHttpRequest();
          this.data = xhr.open("GET", "API/predict") //as mentioned, API/predict returns a valid JSON
          console.log("This data is:" + this.data);
          this.data = xhr1.send("API/predict","_self")
          console.log("This data is_:" + this.data);
      });
    }
  });      
  </script>

For some reason, on the console this.data shows up as undefined both times I'm trying to print it. What am I missing? How to pass the JSON from the API call to the this.data variable?


Solution

  • xhr.send() doesn't return what you want.

    You need to learn XmlHttpRequest first. Here is documentation. And some easy examples

    Simply, you need to listen to onreadystatechange on your xml variable. There you will be able to get data from server.

    Additionaly, why are you using addEventListener. You can simply set on-click.

    <button id="runPredictionButton" on-click="getDataFromServer">
        <i>Button text</i>
    </button>
    

    and then you can define javascript function which is called everytime user clicks on button.

    getDataFromServer: function() {
      var xhr = new XMLHttpRequest();
      xhr.open("GET", "API/predict");
      xhr.send("API/predict","_self");
      xhr.onreadystatechange = function() {
       // 4 = data returned
       if(xhr.readyState == 4) {
         // 200 = OK
         if (this.xhttp.status == 200) {
           // get data
           this.data = xhr.responseText;
         }
       }
      }.bind(this);
    }