есть starter-kit для интернет магазина, не пойму как на полимере сделать отправку форму ajax'ом все перепробовал.
вот как работает на чистом html:
$(document).ready(function() {
//E-mail Ajax Send
$("form").submit(function() { //Change
var th = $(this);
$.ajax({
type: "POST",
url: "mail.php", //Change
data: th.serialize()
}).done(function() {
alert("Спасибо, заявку приняли!",th);
setTimeout(function() {
// Done Functions
th.trigger("reset");
}, 1000);
});
return false;
});
});
это php скрипт:
<?php
$method = $_SERVER['REQUEST_METHOD'];
//Script Foreach
$c = true;
if ( $method === 'POST' ) {
$project_name = trim($_POST["project_name"]);
$admin_email = trim($_POST["admin_email"]);
$form_subject = trim($_POST["form_subject"]);
foreach ( $_POST as $key => $value ) {
if ( $value != "" && $key != "project_name" && $key != "admin_email" && $key != "form_subject" ) {
$message .= "
" . ( ($c = !$c) ? '<tr>':'<tr style="background-color: #f8f8f8;">' ) . "
<td style='padding: 10px; border: #e9e9e9 1px solid;'><b>$key</b></td>
<td style='padding: 10px; border: #e9e9e9 1px solid;'>$value</td>
</tr>
";
}
}
} else if ( $method === 'GET' ) {
$project_name = trim($_GET["project_name"]);
$admin_email = trim($_GET["admin_email"]);
$form_subject = trim($_GET["form_subject"]);
foreach ( $_GET as $key => $value ) {
if ( $value != "" && $key != "project_name" && $key != "admin_email" && $key != "form_subject" ) {
$message .= "
" . ( ($c = !$c) ? '<tr>':'<tr style="background-color: #f8f8f8;">' ) . "
<td style='padding: 10px; border: #e9e9e9 1px solid;'><b>$key</b></td>
<td style='padding: 10px; border: #e9e9e9 1px solid;'>$value</td>
</tr>
";
}
}
}
$message = "<table style='width: 100%;'>$message</table>";
function adopt($text) {
return '=?UTF-8?B?'.Base64_encode($text).'?=';
}
$headers = "MIME-Version: 1.0" . PHP_EOL .
"Content-Type: text/html; charset=utf-8" . PHP_EOL .
'From: '.adopt($project_name).' <'.$admin_email.'>' . PHP_EOL .
'Reply-To: '.$admin_email.'' . PHP_EOL;
mail($admin_email, adopt($form_subject), $message, $headers );
как тоже самое с полимером сделать не могу разобраться, пробовал iron-ajx - https://www.webcomponents.org/element/PolymerElements/iron-ajax не могу отправить данные с формы -- заполненый емай, на скипт php и обработать его.
вот форма и обработчик в полимере - метод _submit
.
<dom-module id="shop-checkout">
<template>
<div class="main-frame">
<iron-pages id="pages" selected="[[state]]" attr-for-selected="state">
<div state="init">
<iron-form id="checkoutForm"
on-iron-form-response="_didReceiveResponse"
on-iron-form-presubmit="_willSendRequest">
<form method="post" action="data/sample_success_response.json">
<div class="subsection" visible$="[[!_hasItems]]">
<p class="empty-cart">Your <iron-icon icon="shopping-cart"></iron-icon> is empty.</p>
</div>
<header class="subsection" visible$="[[_hasItems]]">
<h1>Checkout</h1>
<span>Shop is a demo app - form data will not be sent</span>
</header>
<div class="subsection grid" visible$="[[_hasItems]]">
<section>
<h2 id="accountInfoHeading">Account Information</h2>
<div class="row input-row">
<shop-input>
<input type="email" id="accountEmail" name="accountEmail"
placeholder="Email" autofocus required
aria-labelledby="accountEmailLabel accountInfoHeading">
<shop-md-decorator error-message="Invalid Email" aria-hidden="true">
<label id="accountEmailLabel">Email</label>
<shop-underline></shop-underline>
</shop-md-decorator>
</shop-input>
</div>
<shop-button responsive id="submitBox">
<input type="button" on-click="_submit" value="Place Order">
</shop-button>
</div>
</form>
</iron-form>
</div>
<!-- Success message UI -->
<header state="success">
<h1>Thank you</h1>
<p>[[response.successMessage]]</p>
<shop-button responsive>
<a href="/">Finish</a>
</shop-button>
</header>
<!-- Error message UI -->
<header state="error">
<h1>We couldn´t process your order</h1>
<p id="errorMessage">[[response.errorMessage]]</p>
<shop-button responsive>
<a href="/checkout">Try again</a>
</shop-button>
</header>
</iron-pages>
</div>
<!-- Handles the routing for the success and error subroutes -->
<app-route
active="{{routeActive}}"
data="{{routeData}}"
route="[[route]]"
pattern="/:state">
</app-route>
<!-- Show spinner when waiting for the server to repond -->
<paper-spinner-lite active="[[waiting]]"></paper-spinner-lite>
</template>
<script>
class ShopCheckout extends Polymer.Element {
static get is() { return 'shop-checkout'; }
static get properties() { return {
/**
* The route for the state. e.g. `success` and `error` are mounted in the
* `checkout/` route.
*/
route: {
type: Object,
notify: true
},
/**
* The total price of the contents in the user's cart.
*/
total: Number,
/**
* The state of the form. Valid values are:
* `init`, `success` and `error`.
*/
state: {
type: String,
value: 'init'
},
/**
* An array containing the items in the cart.
*/
cart: Array,
/**
* The server's response.
*/
response: Object,
/**
* If true, the user must enter a billing address.
*/
hasBillingAddress: {
type: Boolean,
value: false
},
/**
* If true, shop-checkout is currently visible on the screen.
*/
visible: {
type: Boolean,
observer: '_visibleChanged'
},
/**
* True when waiting for the server to repond.
*/
waiting: {
type: Boolean,
readOnly: true,
reflectToAttribute: true
},
/**
* True when waiting for the server to repond.
*/
_hasItems: {
type: Boolean,
computed: '_computeHasItem(cart.length)'
}
}}
static get observers() { return [
'_updateState(routeActive, routeData)'
]}
_submit(e) {
if (this._validateForm()) {
// To send the form data to the server:
// 2) Remove the code below.
// 3) Uncomment `this.$.checkoutForm.submit()`.
this.$.checkoutForm.dispatchEvent(new CustomEvent('iron-form-presubmit', {
composed: true}));
this._submitFormDebouncer = Polymer.Debouncer.debounce(this._submitFormDebouncer,
Polymer.Async.timeOut.after(1000), () => {
this.$.checkoutForm.dispatchEvent(new CustomEvent('iron-form-response', {
composed: true, detail: {
response: {
success: 1,
successMessage: 'Demo checkout process complete.'
}
}}));
});
// this.$.checkoutForm.submit();
}
}
/**
* Sets the valid state and updates the location.
*/
_pushState(state) {
this._validState = state;
this.set('route.path', state);
}
/**
* Checks that the `:state` subroute is correct. That is, the state has been pushed
* after receiving response from the server. e.g. Users can only go to `/checkout/success`
* if the server responsed with a success message.
*/
_updateState(active, routeData) {
if (active && routeData) {
let state = routeData.state;
if (this._validState === state) {
this.state = state;
this._validState = '';
return;
}
}
this.state = 'init';
}
/**
* Sets the initial state.
*/
_reset() {
let form = this.$.checkoutForm;
this._setWaiting(false);
form.reset();
let nativeForm = form._form;
if (!nativeForm) {
return;
}
// Remove the `aria-invalid` attribute from the form inputs.
for (let el, i = 0; el = nativeForm.elements[i], i < nativeForm.elements.length; i++) {
el.removeAttribute('aria-invalid');
}
}
/**
* Validates the form's inputs and adds the `aria-invalid` attribute to the inputs
* that don't match the pattern specified in the markup.
*/
_validateForm() {
let form = this.$.checkoutForm;
let firstInvalid = false;
let nativeForm = form._form;
for (let el, i = 0; el = nativeForm.elements[i], i < nativeForm.elements.length; i++) {
if (el.checkValidity()) {
el.removeAttribute('aria-invalid');
} else {
if (!firstInvalid) {
// announce error message
if (el.nextElementSibling) {
this.dispatchEvent(new CustomEvent('announce', {bubbles: true, composed: true,
detail: el.nextElementSibling.getAttribute('error-message')}));
}
if (el.scrollIntoViewIfNeeded) {
// safari, chrome
el.scrollIntoViewIfNeeded();
} else {
// firefox, edge, ie
el.scrollIntoView(false);
}
el.focus();
firstInvalid = true;
}
el.setAttribute('aria-invalid', 'true');
}
}
return !firstInvalid;
}
/**
* Adds the cart data to the payload that will be sent to the server
* and updates the UI to reflect the waiting state.
*/
_willSendRequest(e) {
let form = e.target;
let body = form.ajax && form.ajax.body;
this._setWaiting(true);
if (!body) {
return;
}
// Populate the request body where `cartItemsId[i]` is the ID and `cartItemsQuantity[i]`
// is the quantity for some item `i`.
body.cartItemsId = [];
body.cartItemsQuantity = [];
this.cart.forEach((cartItem) => {
body.cartItemsId.push(cartItem.item.name);
body.cartItemsQuantity.push(cartItem.quantity);
});
}
/**
* Handles the response from the server by checking the response status
* and transitioning to the success or error UI.
*/
_didReceiveResponse(e) {
let response = e.detail.response;
this.response = response;
this._setWaiting(true);
if (response.success) {
this._pushState('success');
this._reset();
this.dispatchEvent(new CustomEvent('clear-cart', {bubbles: true, composed: true}));
} else {
this._pushState('error');
}
}
_toggleBillingAddress(e) {
this.hasBillingAddress = e.target.checked;
if (this.hasBillingAddress) {
this.$.billAddress.focus();
}
}
_computeHasItem(cartLength) {
return cartLength > 0;
}
_formatPrice(total) {
return isNaN(total) ? '' : '$' + total.toFixed(2);
}
_getEntryTotal(entry) {
return this._formatPrice(entry.quantity * entry.item.price);
}
_visibleChanged(visible) {
if (!visible) {
return;
}
// Reset the UI states
this._reset();
// Notify the page's title
this.dispatchEvent(new CustomEvent('change-section', {
bubbles: true, composed: true, detail: { title: 'Checkout' }}));
}
}
customElements.define(ShopCheckout.is, ShopCheckout);
</script>
</dom-module>