Answer the question
In order to leave comments, you need to log in
How to fix an error when connecting a dynamic form on Yandex Turbo pages?
To all who visit, thank you for your attention!
I connect a dynamic form on a turbo page with 1 field (phone), but it gives an error "No internet connection"
<form data-type="dynamic-form" end_point="https://sitename.ru/includes/form-yandex.php">
<div type="input-block">
<span type="input" name="LEAD_PHONE" label="Телефон" input-type="text" placeholder="8-ХХХ-ХХХ-ХХ-ХХ" required="true"></span>
<button type="submit" text="ПОЛУЧИТЬ ПРЕДЛОЖЕНИЕ"></button>
</div>
<div type="result-block">
<span type="text" field="description"></span>
</div>
</form>
Answer the question
In order to leave comments, you need to log in
Not yet! Since the turbo version of your site opens at https://yandex.ru/turbo?text=Your_site ,
and you want to send the form to https://Your_site , then the browser according to the CORS policy on the page https://yandex.ru/ turbo just won't let you make a cross-domain request. An obvious jamb of Yandex.
Everything works - the main thing is to correctly configure the form processing server. Yandex has an example in php. The domain must match the site's domain.
I give an example on the node
import Cors from "cors";
import initMiddleware from "../../lib/init-middleware";
const cors = initMiddleware(
// You can read more about the available options here: https://github.com/expressjs/cors#configuration-options
Cors({
methods: ["POST", "OPTIONS"],
origin: [
/^(https:\/\/(?:.*\.)?yandex\.(?:ru|by|uz|com|com\.tr))$/,
/^(https:\/\/(?:.*\.)?turbopages.org)$/
],
credentials: true,
})
);
export default async function handler(req, res) {
await cors(req, res);
//остальная логика
res.json([
{
field: "description",
value:
"Спасибо за подписку .Мы сообщим , как только так сразу",
},
{
field: "link",
value: "На главную",
href: "https://batteryhelp.ru",
},
]);
}
I found a solution.
Here is the code of the form (an example from the Yandex Turbo website https://yandex.ru/dev/turbo/doc/rss/elements/dynam... )
<form data-type="dynamic-form" end_point="http://exmaple.com/post-form.php">
<div type="input-block">
<span type="input" name="fio" label="Имя" input-type="text" placeholder="Иван Иванов" required="true"></span>
<span type="input" name="phone" label="Телефон" input-type="text" placeholder="8-ХХХ-ХХХ-ХХ-ХХ" required="true"></span>
<span type="radio" name="delivery" label="Выбор способа доставки">
<span
type="option"
value="pickup"
checked="true"
label="Самовывоз, Бесплатно"
meta="Сегодня">
</span>
<span
type="option"
value="courier1"
checked="false"
label="Курьером, 500₽"
meta="1 день, Внутри МКАД">
</span>
<span
type="option"
value="courier2"
checked="false"
label="Курьером, 1500₽"
meta="Сегодня, Снаружи МКАД">
</span>
</span>
<span type="checkbox" name="sms" value="on" content="СМС оповещение о заказе"></span>
<span type="textarea" name="comment" label="Комментарий" placeholder="Комментарий к заказу" required="false"></span>
<button type="submit" text="Оформить заказ"></button>
</div>
<div type="result-block">
<span type="text" field="description"></span>
<span type="link" field="link"></span>
</div>
</form>
<?php
/**
* Определение возможности доступа к API.
*/
function turbo_get_allow_origin()
{
$http_origin = $_SERVER['HTTP_ORIGIN'];
if (preg_match('/^(https:\/\/(?:.*\.)?yandex\.(?:ru|by|uz|com|com\.tr))$/', $http_origin, $matches)) {
return $matches[0];
} else if (preg_match('/^(https:\/\/(?:.*\.)?turbopages.org)$/', $http_origin, $matches)) {
return $matches[0];
}
return null;
}
$http_allow_origin = turbo_get_allow_origin();
if (is_null($http_allow_origin)) {
// Если доступа нет, должен вернуться код ответа 403.
http_response_code(403);
exit('Access denied');
}
// Отправка CORS-заголовков.
header("Access-Control-Allow-Origin: " . $http_allow_origin);
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Headers: Origin, Content-Type, Content-Length, Accept-Encoding");
// Отправка заголовка о том, что данные возвращаются в формате JSON.
header("Content-Type: application/json;charset=utf-8");
// end code yandex form
// if POST request
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$mailTo = "[email protected]"; // mail to
$mailFrom = "[email protected]"; // mail from
$data_json = file_get_contents("php://input");
$data = json_decode($data_json, true);
// form varibles
$fio = htmlspecialchars($data['fio']);
$phone = htmlspecialchars($data["phone"]);
$delivery = htmlspecialchars($data["delivery"]);
$sms = htmlspecialchars($data["sms"]);
$comment = htmlspecialchars($data["comment"]);
// mail subject text
$subjectText = "Заказ с сайта example.com";
$subject = "=?utf-8?b?" . base64_encode($subjectText) . "?=";
// mail header text
$header = "Content-Type: text/plain; charset=utf-8\n";
$header .= "From: Заказ <" . $mailFrom . ">\n\n";
$message = "\n\nИмя: " . $fio . "\n\nТелефон: " . $phone . "\n\nДоставка: " . $delivery . "\n\nСообщение: " . $sms . "\n\nКоментарий: " . $comment;
$mail = mail($mailTo, $subject, $message, $header);
// output in yandex form
if ($mail) {
echo '[
{
"field": "description",
"value": "Заказ успешно оформлен. Ваш номер заказа:"
},
{
"field": "link",
"value": "123456",
"href": "https://example.com/cabinet/order/123456/"
}
]';
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question