Chris Hawkes
Chris Hawkes

Reputation: 12420

Polymer on-click is double posting

I'm wondering if anybody here has had a similar problem with Polymer double posting a form. My code is very simple, as stated previously, each time I click the button the form is posted twice. I'm using Polymer 05.5

<polymer-element name="book-form">
    <template>
        <label for="title">Title:</label>
        <input id="title" value="{{title}}" />
        <label for="author">Author:</label>
        <input id="author" value="{{author}}" />
        <label for="image">Image:</label>
        <input id="image" value="{{image}}" />
        <button on-click="{{fireAjax}}">Submit Form</button>
        <core-ajax id="ajax"
                   auto
                   url="http://localhost:45922/api/book"
                   handleAs="json"
                   method="POST"
                   >
        </core-ajax>     
    </template>
    <script>
        Polymer({
            fireAjax: function () {
                var data = { image: this.image, author: this.author, title: this.title };
                this.$.ajax.contentType = 'application/json';
                this.$.ajax.body = JSON.stringify(data);
                this.$.ajax.go();
            }
        });
    </script>
</polymer-element>

Upvotes: 0

Views: 198

Answers (2)

Luc Hendriks
Luc Hendriks

Reputation: 2533

Your fireAjax function changes the data of the core-ajax. Because auto is on, the ajax call is fired. Then you call this.$.ajax.go() so the call is fired again.

Try to remove the auto in the core-ajax element.

Upvotes: 2

Chris Hawkes
Chris Hawkes

Reputation: 12420

Okay I see what the problem is, the auto property on the form post anytime the url or the parameters change. If one wants to control when the POST takes place they should remove the auto property from core-ajax.

<polymer-element name="book-form">
    <template>
        <label for="title">Title:</label>
        <input id="title" value="{{title}}" />
        <label for="author">Author:</label>
        <input id="author" value="{{author}}" />
        <label for="image">Image:</label>
        <input id="image" value="{{image}}" />
        <button on-click="{{test}}">Submit Form</button>
        <core-ajax id="ajax"
                   url="http://localhost:45922/api/book"
                   handleAs="json"
                   method="POST"
                   >
        </core-ajax>     
    </template>
    <script>
        Polymer('book-form', {
            test: function () {
                var data = { image: this.image, author: this.author, title: this.title };
                this.$.ajax.contentType = 'application/json';
                this.$.ajax.body = JSON.stringify(data);
                this.$.ajax.go();
            }
        });
    </script>
</polymer-element>

Upvotes: 0

Related Questions