Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iron Ajax - How to access Response from on-response function?

Tags:

polymer

I have this element:

<template>
...
<iron-ajax 
   id="ajax" 
   url="..." 
   handle-as="json" 
   verbose=true 
   last-response={{ajaxResponse}} 
   loading="{{cargando}}"
   on-response="_handleResponse"> 
</iron-ajax>

<div id="resultado"></div>
</template>

<script>
    Polymer({
        ...

        _handleResponse: function(event){
            console.log("_handleResponse... ");
            // this.$.resultado.innerHTML = event.detail.innerHTML;
        }
    });
</script>

The response I see in Firebug is:

<p>Hello word</p>

I want to access the response in _handleResponse function in order to set it as innerHTML of the resultado div, but nothing works.

I have tried:

  • event.detail.innerHTML
  • event.detail.response
  • event.detail.xhr.response
  • event.detail.xhr.responseText
  • event.detail.request.xhr.response (This route doesn't exist. How can it be the solution in Polymer Iron Ajax - How to access Response from Request after Error Event??)

If I debug and watch e.detail.response value when in on-response function:

e.detail.response is null

In network tab I can see the response (simple 'hello'):

Response in network tab

like image 554
Jaime Avatar asked Nov 28 '16 17:11

Jaime


1 Answers

The response data is in fact returned in event.detail.response of the <iron-ajax>.response event. Your response field is null because you've misconfigured <iron-ajax>.handleAs. When you set it to json, the Accept-Type header is set to application/json and any response would be parsed with JSON.parse(). If your server ignores Accept-Type and sends whatever it wants, <iron-request> will attempt to parse the response as JSON and fail, causing a null response body per the spec. Note that hello and <p>Hello</p> are not valid JSON strings.

If you want to receive plaintext data, set <iron-ajax>.handleAs to text (the default is json).

Demo of <iron-ajax handle-as="text">

Demo of <iron-ajax handle-as="json">


  • event.detail.request.xhr.response (This route doesn't exist. How can it be the solution in Polymer Iron Ajax - How to access Response from Request after Error Event??)

The question you linked asks about the <iron-ajax>.error event, which has a different event detail than the <iron-ajax>.response event.

When <iron-ajax> receives a server response, it fires the response event with the corresponding <iron-request> as the event detail.

If the request fails for any reason, <iron-ajax> fires the error event with an object (containing the iron-request via the request attribute, and the underlying error via error) as the event detail.

like image 196
tony19 Avatar answered Sep 27 '22 17:09

tony19