user736893
user736893

Reputation:

How do I access core-ajax response data via javascript?

For instance, if I have the following code in an auto-binding template inside my index.html file:

index.html

<template is="auto-binding">
    <core-ajax id="ds" auto url="url/to/data.json" response="{{data}}"></core-ajax>
    <my-items items="{{data}}"></my-items>
</template>

app.js

(function(document) {
  'use strict';

    document.addEventListener('polymer-ready', function() {
        var responseData = ????
    });
})(wrap(document));

Upvotes: 1

Views: 1045

Answers (1)

robdodson
robdodson

Reputation: 6786

Typically we use data binding with core-ajax, but if you need to get at it with JS you can either get the response out of the core-response event that core-ajax fires, or you can look at the response property of the core-ajax tag itself. jsbin example

<core-ajax auto url="http://date.jsontest.com"></core-ajax>

<script>
  document.addEventListener('polymer-ready', function() {
    var ajax = document.querySelector('core-ajax');
    ajax.addEventListener('core-response', function(e) {
      console.log(e.detail.response);
      // or
      console.log(e.target.response);
      // or
      console.log(ajax.response);
    });
  });
</script>

edit: OP wants to get at a core-ajax element inside an auto binding template

You should listen for the template-bound event fired by the auto-binding template when it stamps its content to the page. Then you can querySelector for core-ajax. jsbin example

<template is="auto-binding">
  <core-ajax auto url="http://date.jsontest.com"></core-ajax>
</template>

<script>
  var tmpl = document.querySelector('template');
  tmpl.addEventListener('template-bound', function() {
    var ajax = document.querySelector('core-ajax');
    ajax.addEventListener('core-response', function(e) {
      console.log(e.detail.response);
      // or
      console.log(e.target.response);
      // or
      console.log(ajax.response);
    });
  });
</script>

edit: To show a nicer approach

Since the original poster was specifically asking about getting the response using JavaScript, I gave the fully JS approach. You can clean this up quite a bit using bindings. jsbin example

<template is="auto-binding">
  <core-ajax auto
             response="{{data}}"
             on-core-response="{{ajaxHandler}}"
             url="http://date.jsontest.com"
             handleAs="json"></core-ajax>
  <h1>{{data.date}}: {{data.time}}</h1>
</template>

<script>
  addEventListener('template-bound', function(e) {
    // do something else with response
    e.target.ajaxHandler = function(event) {
      console.log(event.target.response);
    }
  });
</script>

Upvotes: 2

Related Questions