polymerpolymer-3.xiron-ajax

How to trigger iron-ajax on button click in Polymer-3.x?


I am creating a polymer element which uses iron-ajax. This will hit a public API to fetch a random fox imageUrl and dispaly in DOM.

Requirement

On clicking button, i want to make a new call to the api, this will give me new url. Currently i am using <button type="button" onClick="window.location.reload();">. but this refreshes page.

Problem

I went through this StackOverflow solution and changed it to version-3 solution.

class MyFox extends PolymerElement {
  static get template() {
    return html`
      <dom-bind>
      <template id="temp"> 
          <iron-ajax
            auto
            id="dataAjax"
            url=""
            handle-as="json"
            on-response="handleResponse"
            id="apricot">
          </iron-ajax>

          <button type="button" onClick="window.location.reload();">Next Image</button>
          <br> <br>
          <img src="[[imgUrl]]" width="300">
      </template>
      </dom-bind>
    `;
  }
  static get properties() {
    return {
      prop1: {
        type: String,
        value: 'my-fox',
      },
      imgUrl: {
        type: String,
      }
    };
  }
  handleResponse(event, res) {
    this.imgUrl = res.response.image; 
  }
  nextImg() {
    // new call to iron-ajax for new image
    var temp = document.querySelector('#temp');
    temp.$.dataAjax.generateRequest();
  }
}

window.customElements.define('my-fox', MyFox);

But i am getting the following error. listener method handleResponse not defined

fox error

Question

How to manually trigger iron-ajax on button click, so I can get new response or imageUrl and the page is not refreshed?


Solution

  • There are a couple errors in your web component

    class MyFox extends PolymerElement {
      static get template() {
        return html`
              <iron-ajax
                auto
                id="dataAjax"
                url=""
                handle-as="json"
                on-response="handleResponse">
              </iron-ajax>
    
              <button type="button" on-tap="nextImg">Next Image</button>
              <br> <br>
              <img src="[[imgUrl]]" width="300">
        `;
      }
      static get properties() {
        return {
          prop1: {
            type: String,
            value: 'my-fox',
          },
          imgUrl: {
            type: String,
          }
        };
      }
      handleResponse(event, res) {
        this.imgUrl = res.response.image; 
      }
      nextImg() {
        // new call to iron-ajax for new image
        this.$.dataAjax.generateRequest();
      }
    }
    
    window.customElements.define('my-fox', MyFox);