polymerweb-componentpolymer-3.xiron-ajaxiron-form

How to submit iron-form via ajax in Polymer 3


The Problem

I want to submit an iron-form in Polymer 3. I use a paper-button and the form has to be submitted via iron-ajax.

This is my view.js

import { PolymerElement, html } from '@polymer/polymer/polymer-element.js';
import './shared-styles.js';

class Foo extends PolymerElement {
    static get template() {
        return html'
            <iron-form>
                <form id="formOne" method="post" action="https://my-api-url.com" is="iron-form">
                    <paper-input name="input-1" placeholder="Input One"></paper-input>
                    <paper-button on-tap="submitHandler">Submit</paper-button>
                </form>
            </iron-form>
        ';
    }

    submitHandler() {
        this.$.formOne.generateRequest();
    }
}
window.customElements.define('foo', Foo);

My form is not submitted when clicking the paper-button.

What I tried

Any help is highly appreciated. Thanks!


Solution

  • I tried submitting the form with this.$.formOne.submit(). That worked, too. Of course the form wasn't submitted via ajax but the api page was opened.

    The issue is you're incorrectly calling <form>.submit() (executes the synchronous submit method of the native <form>) instead of <iron-form>.submit(). To resolve the issue, move the ID to the <iron-form>, which would execute the intended asynchronous submit method:

    <iron-form id="formOne">
      <!-- <form id="formOne"> --> <!-- DON'T DO THIS -->
      <form>...</form>
    </iron-form>
    

    demo