2

I would like <iron-ajax> to POST dynamic data from a <textarea> to http://example.net when I click a <paper-button> element:

function get_data() {
  return {content:document.getElementById("mycontent").html()}
}
<html>
  <head>
    <!-- Imports-->
  </head>
  <body>
    <iron-ajax
      url="//example.net"
    ></iron-ajax>
    <paper-button id="mybutton"></paper-button>
    <textarea id="mycontent"></textarea>
  </body>
</html>

How can I combine the iron-ajax and paper-button elements to send the data to the server?

Sebastian Wozny
  • 16,943
  • 7
  • 52
  • 69

3 Answers3

7

You need to wrap your polymer elements in a tag that will register as polymer element. You can use dom-bind in your case.

<template id="t" is="dom-bind">           
    <textarea value="{{dataToPost::input}}"></textarea>
    <paper-button on-tap="postData">Post Data</paper-button>
    <iron-ajax 
    id="dataAjax" 
    method="post"
    url="data/url"
    on-response="postComplete"></iron-ajax>
</template>  

In the script you need to call generateReqeust on iron-ajax element.

(function (document) {
'use strict';
document.addEventListener('WebComponentsReady', function() {

    // We have to bind the template with the model
    var t = document.querySelector('#t');
    var ajaxRequest = t.$.dataAjax;

    // make the iron-ajax call
    t.postData = function() {
      ajaxRequest.body = {
        'text': t.dataToPost;
      } 
      ajaxRequest.generateRequest();
    }

    //callback on request complete
    t.postComplete = function(){
      alert('whoa! request complete');
    }
});
})(document);

Working plunker for GET: http://plnkr.co/edit/13QJ7QFETIBg4bEiCMS7?p=preview

Srik
  • 2,341
  • 2
  • 21
  • 35
1

The simplest and least expensive way is to just query the iron ajax element and call the method generateRequest()

Place this in your on-tap handler for paper-button...

Polymer.dom(this.root).querySelector('iron-ajax').generateRequest()

dman
  • 10,406
  • 18
  • 102
  • 201
0

If you are keen on not using a <template is="dom-bind"> (it would make it a lot easier though), you can go the plain vanilla route (i.e. no dom-bind).

<html>

<head>
  <!-- Imports-->
</head>

<body>
  <iron-ajax url="//example.net"></iron-ajax>
  <paper-button id="mybutton"></paper-button>
  <textarea id="mycontent"></textarea>
  <script>
    window.addEventListener('WebComponentsReady', function() {
      var ironAjax = document.querySelector('iron-ajax');
      ironAjax.method = 'post';
      ironAjax.contentType = 'text/plain'; // you're just sending text
      var myButton = document.getElementById('mybutton');
      var myContent = document.getElementById('mycontent');

      myButton.addEventListener('tap', function(e) {
        var valueToSend = myContent.value;
        ironAjax.body = valueToSend;
        ironAjax.generateRequest();
      });
    });
  </script>
</body>

</html>
Neil John Ramal
  • 3,734
  • 13
  • 20