chaseme
chaseme

Reputation: 29

iron-request doesn't make more than one request

I am working with the Polymer 2 library. Whenever I try to make multiple requests using iron-request, the code only ever seems to make a POST request on the first initiation. Any subsequent requests seem to be ignored, even when data that is set to be sent to the server is different from the initial request.

I've written a small example in this Plunker: https://plnkr.co/edit/cozVKUdQ2q2SV46rcCTL?p=preview

I created a iron-request and a button element to initiate the request like so:

<paper-button on-click="save" class="green">Send</paper-button>
...
<iron-request id="xhr"></iron-request>

The save function is setup to take text from a textarea and send that off to a server.

save() {
    var response = this.$.xhr.send({
      url: "https://httpbin.org/post",
      headers: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      body: {
        content: this.inputdata
      },
      method: "POST"
    });
    var poly = this;
    this.$.xhr.completes.then(function(data) {
      console.log("finished");
      poly.$.responsetext.innerHTML = data.response;
    })

The code in question is in the "element1.html" file. If you try sending different text payloads, only the first request will be send. (You can see in the response box that the form "content" field stays the same.)

Any idea what is going on? I'm thinking that I would have to create new iron-request elements everytime I need to make a new request... but that doesn't sound like a very elegant solution.

Upvotes: 1

Views: 367

Answers (1)

Maria
Maria

Reputation: 5604

As you suspected, iron-request has been built to send a single HTTP request. I had a quick look at the its implementation. The send method will actually just return null and not do anything, if the request has a status that is larger 0 than, which will be the case if you have used it before.

While you could create a new iron-request element for each request, it is not elegant (as you said yourself). Instead, you could work with iron-ajax. You can find some instructions on its documentation page.

Your <iron-request> can be rewritten as this.

<iron-ajax id="xhr" url="https://httpbin.org/post" content-type="application/x-www-form-urlencoded" method="POST" body="[[inputdata]]" on-response="onXhrSuccess"></iron-ajax>

Your save function,

save() {
    this.$.xhr.generateRequest();
}

onXhrSuccess(event, request) {
    console.log("finished");
    poly.$.responsetext.innerHTML = event.detail.response;
}

Upvotes: 2

Related Questions