简体   繁体   中英

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

  • I created a iron-ajax element manually and did a request with generateRequest() . That worked.
  • I put an alert in the submitHandler function. It was shown.
  • 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.
  • I created a normal <button> to submit the form. This works and also sends the form via ajax, but I want to use the paper-button.

Any help is highly appreciated. Thanks!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM