Я попытался создать форму SweetAlert с 3 входами (имя, адрес электронной почты, текст). Эта форма после отправки должна отправить данные формы на адрес электронной почты администратора. Сделал и все работает! Но я уверен, что мой код контроллера недействителен.
CMS: OpenCart 2.3 + SweetAlert 2.
Вот форма SweetAlert + запрос Ajax:
<script type = "text/javascript">
window.onload = function () {
var a = document.getElementById('director');
a.onclick = function() {
Swal({
type: 'warning',
title: 'Your message',
html:
'<input name = "name" id = "swal-input1" class = "swal2-input" placeholder = "Your name">' +
'<input name = "email" id = "swal-input2" class = "swal2-input" placeholder = "Email">' +
'<textarea name = "text" id = "swal-textarea1" class = "swal2-textarea" placeholder = "Enter your text..." style = "display: flex;"></textarea>',
showCancelButton: true,
confirmButtonColor: '#ff5908',
cancelButtonColor: '#666',
confirmButtonText: 'Send',
cancelButtonText: 'Cancel',
preConfirm: function () {
return new Promise(function (resolve) {
resolve([
$('#swal-input1').val(),
$('#swal-input2').val(),
$('#swal-textarea1').val()
])
})
},
}).then(function (result) {
if (result.value) {
var result = {};
result.name = $('#swal-input1').val();
result.email = $('#swal-input2').val();
result.text = $('#swal-textarea1').val();
var data = JSON.stringify(result);
$.ajax({
url:"index.php?route=common/message/index",
type: "post",
data: data,
dataType: "json",
success: function() {Swal({type: 'success', text: 'Message sent'});},
error: function(xhr,status,error){
console.info(status);
console.info(error);
}
})
}
})
return false;
}
}
</script>После этого ajax-запрос отправляется контроллеру «Сообщение» в метод «индексирования».
<?php
class ControllerCommonMessage extends Controller {
public function index() {
$request_body = file_get_contents('php://input');
$data = json_decode($request_body);
$username = $data->name;
$email = $data->email;
$msg = $data->text;
$subject = 'Test email from: '.$email;
$mail = new Mail();
$mail->protocol = $this->config->get('config_mail_protocol');
$mail->parameter = $this->config->get('config_mail_parameter');
$mail->smtp_hostname = $this->config->get('config_mail_smtp_hostname');
$mail->smtp_username = $this->config->get('config_mail_smtp_username');
$mail->smtp_password = html_entity_decode($this->config->get('config_mail_smtp_password'), ENT_QUOTES, 'UTF-8');
$mail->smtp_port = $this->config->get('config_mail_smtp_port');
$mail->smtp_timeout = $this->config->get('config_mail_smtp_timeout');
$mail->setTo('[email protected]');
$mail->setFrom($this->config->get('config_email'));
$mail->setSender(html_entity_decode($this->config->get('config_name'), ENT_QUOTES, 'UTF-8'));
$mail->setSubject(html_entity_decode($subject, ENT_QUOTES, 'UTF-8'));
$mail->setHtml($msg);
$mail->send();
}
}Итак, форма работает, сообщения отправлены успешно. Но этот фрагмент кода мне не нравится:
$request_body = file_get_contents('php://input');
$data = json_decode($request_body);
Я тоже пробовал писать вот так:
if (isset($this->request->post['data'])) {
$result = $this->request->post['data'];
var_dump($result);
} else {
echo 'empty';
}
Но ничего не работает. "результат" пуст. Что я делаю не так?
Отлично! Спасибо большое! Я изменил строку: data: data на: data: {data: result} и удалил var data = JSON.stringify (result); И это работает! Большое тебе спасибо!






проверьте эту ссылку: stackoverflow.com/questions/10955017/…