Skip to content

Instantly share code, notes, and snippets.

@Prroffessorr
Last active May 19, 2021 07:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Prroffessorr/5f69d0feafbf42598e644d7c2ff090b3 to your computer and use it in GitHub Desktop.
Save Prroffessorr/5f69d0feafbf42598e644d7c2ff090b3 to your computer and use it in GitHub Desktop.
Форма отправки сообщений с сохранением содержимого полей (Использование суперглобальной переменной $_SESSION и setcookie)
<?php
//Не забываем в начале инициализировать нашу сессию
session_start();
?>
<form action="<?php bloginfo("template_directory");?>/session_ajax_form.php" class="pdfmodal__form" method="post">
<div>
<label for="surname"><?php _e("ФИО*"); ?></label><br>
<input required name="surname" id="surname" type="text" value="<?php echo $_SESSION['surname']; ?>">
</div>
<div>
<label for="phone"><?php _e("Номер телефона*"); ?></label><br>
<input required name="phone" id="phone" type="phone" value="<?php echo $_SESSION['phone']; ?>">
</div>
<?php
//Данная форма использовалась как форма оформления заказа на сайте магазина
//Повторитель в данном случае выступает возможностью добавить несколько полей для ввода сообщений
for($i=1; $i<=5; $i++): ?>
<div class="<?php if($i<=1){ ?> pdfmodal__shortinputs list-<?php echo $i; ?> <?php } else{ ?> list-<?php echo $i; ?> pdfmodal__hide <?php } ?> ">
<div>
<label for="articul"><?php _e("Артикул"); ?></label><br>
<input name="articul-<?php echo $i; ?>" id="articul" type="text" value="<?php echo $_SESSION["articul-".$i.""]; ?>">
</div>
<div>
<label><?php _e("Марка"); ?></label><br>
<input name="rac-<?php echo $i; ?>" id="rac" type="text" value="<?php echo $_SESSION["rac-".$i.""]; ?>">
</div>
<div>
<label for="size"><?php _e("Наименование"); ?></label><br>
<input name="size-<?php echo $i; ?>" id="size" type="text" value="<?php echo $_SESSION["size-".$i.""]; ?>">
</div>
<div>
<label for="amount"><?php _e("Количество"); ?></label><br>
<input name="amount-<?php echo $i; ?>" id="amount" type="number" value="<?php echo $_SESSION["amount-".$i.""]; ?>">
</div>
</div>
<?php
endfor; ?>
<div class="pdfmodal__addmore">
<img class="pdfmodal__addmorebtn"
src="<?php echo get_stylesheet_directory_uri(); ?>/img/icons/addmore.svg" alt="">
</div>
<div>
<label for="name"><?php _e("Ваше сообщение"); ?></label><br>
<textarea name="text" id="text"><?php echo $_SESSION['text']; ?></textarea>
</div>
<div>
<input type="checked" id="save_or_send_checkbox" hidden="true">
<input type="text" name="save_or_send" id="set_cookies_send" hidden="true">
<button class="hidden_set_cookie" hidden="true">Cохранение кукисов</button>
<button class="button buttonwhite"><?php _e("Отправить"); ?></button>
</div>
</form>
<script src="<?php echo get_stylesheet_directory_uri(); ?>/js/addmore.js"></script>
<script>
//Ипользуем сессионное хранилище для того чтобы всегда знать сколько полей для ввода пользователь уже выбрал
var num = sessionStorage.getItem('test');
if(num > 1){
for(var i=0; i<=num;i++){
$(".pdfmodal__hide.list-"+i).addClass("pdfmodal__shortinputs");
$(".pdfmodal__shortinputs.list-"+i).removeClass("pdfmodal__hide");
}
}
</script>
var num = 2;
jQuery(document).ready(function($){
$('.pdfmodal__addmorebtn').click(function(){
num=num+1;
$(".pdfmodal__hide.list-"+num).addClass("pdfmodal__shortinputs");
$(".pdfmodal__shortinputs.list-"+num).removeClass("pdfmodal__hide");
sessionStorage.setItem('test', num);
});
});
$(document).ready(function () {
//Сохраняеем кукусы каждые 5 секунд
window.setInterval(function () {
$(".hidden_set_cookie").trigger("click");
}, 5000);
function save_send(value) {
$("#set_cookies_send").val(value);
}
//Нажатие кнопки "Сохранить" (Происходит каждые 5 секунд)
$(".hidden_set_cookie").on("click", function () {
document.getElementById("surname").required = false;
document.getElementById("phone").required = false;
document.getElementById("save_or_send_checkbox").checked = true;
});
//Нажатие кнопки "Отправить"
$(".button").on("click", function () {
document.getElementById("surname").required = true;
document.getElementById("phone").required = true;
document.getElementById("save_or_send_checkbox").checked = false;
});
//Отправка соббщения
$("form").submit(function (event) {
event.preventDefault();
//Устанавливаем значиние (либо схранить либо отправить)
if(document.getElementById("save_or_send_checkbox").checked==true){
save_send(0);
}else{
save_send(1);
sessionStorage.removeItem('test');
}
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
data: new FormData(this),
contentType: false,
cache: false,
processData: false,
success: function (result) {
if(result!="Cookie saved"){
$(".pdfmodal__form")[0].reset();
console.log(result);
}else{
console.log(result);
}
}
});
});
});
<?php
session_start();
require_once '../../../wp-load.php';
//Сохраняем или отправляем сесиионные переменные (для этого используется функция save_send(); в файле session_ajax_form.js)
if($_POST['save_or_send'] == "0"){
$surname=$_POST['surname'];
$phone=$_POST['phone'];
$text=$_POST['text'];
for($i=1; $i<=5; $i++):
$_SESSION["articul-".$i.""]=$_POST["articul-".$i.""];
$_SESSION["rac-".$i.""]=$_POST["rac-".$i.""];
$_SESSION["size-".$i.""]=$_POST["size-".$i.""];
$_SESSION["amount-".$i.""]=$_POST["amount-".$i.""];
endfor;
ob_start();
setcookie('surname', $name,time()+60 );
setcookie('phone', $phone,time()+60 );
setcookie('phone', $text,time()+60 );
//Устанавливаем кукисы для полей ввода
for($i=1; $i<=5; $i++):
if($_POST["articul-".$i.""] || $_POST["rac-".$i.""] || $_POST["size-".$i.""] || $_POST["amount-".$i.""]){
setcookie("articul-".$i."", $_POST["articul-".$i.""],time()+60 );
setcookie("rac-".$i."", $_POST["rac-".$i.""],time()+60 );
setcookie("size-".$i."", $_POST["size-".$i.""],time()+60 );
setcookie("amount-".$i."", $_POST["amount-".$i.""],time()+60 );
}
endfor;
ob_flush();
$_SESSION['surname']=$surname;
$_SESSION['phone']=$phone;
$_SESSION['text']=$text;
echo "Cookie saved";
}
//Отправляем данные на почту
else{
$surname = $_SESSION['surname'];
$phone = $_SESSION['phone'];
$text = $_SESSION['text'];
if($surname && $phone){
$mail_to = get_option('admin_email');
if($surname = trim(htmlspecialchars($_POST['surname']))){
$message .=
'
ФИО :'.$surname;}
if($phone = trim(htmlspecialchars($_POST['phone']))){
$message .=
'
Телефон :'.$phone;}
if($text = trim(htmlspecialchars($_POST['text']))){
$message .=
'
Комментарий :'.$text;}
//Получаем сессионные данные для полей (артикул, марка, размер, количество )
for($i=1; $i<=5; $i++):
if($_SESSION["articul-".$i.""] || $_SESSION["rac-".$i.""] || $_SESSION["size-".$i.""] || $_SESSION["amount-".$i.""]){
$message .=
'
Артикул :'.$_SESSION["articul-".$i.""].
" Марка :".$_SESSION["rac-".$i.""].
" Наименование :".$_SESSION["size-".$i.""].
" Количество :".$_SESSION["amount-".$i.""];
}
endfor;
$email_subject = "Форма с сохранением состояния (Made by ITХищник)";
if (wp_mail($mail_to, $email_subject, $message)){
echo json_encode('ok');
}else{
echo json_encode('err');
}
echo($message);
}
session_unset();
session_destroy();
die();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment