Commit de4b99aa authored by Shakarim Sapa's avatar Shakarim Sapa

- Изменили логику подписки

parent e689c350
......@@ -5,6 +5,7 @@ namespace common\modules\cases\controllers;
use Yii;
use common\components\BaseController;
use common\modules\cases\models\CasesBids;
use yii\helpers\Json;
use yii\web\NotFoundHttpException;
use yii\web\Response;
use yii\widgets\ActiveForm;
......@@ -31,20 +32,24 @@ class DefaultController extends BaseController
}
/**
* @return array
* @throws NotFoundHttpException
* @throws \Exception
* @param $email
* @throws \yii\web\NotFoundHttpException
*/
public function actionAdd(){
public function actionAdd($email){
Yii::$app->response->format = Response::FORMAT_JSON;
// Получили дату
$date = new \DateTime();
// Создали модель
$model = new CasesBids();
// Результирующий массив
$result = [
'result' => false
];
// Получили и переопределили данные из формы
if(Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
if(Yii::$app->request->isAjax) {
// Переопределили дату
$model->date = $date->format('Y-m-d H:i:s');
$model->email = $email;
// Открыли транзакцию
$transaction = Yii::$app->db->beginTransaction();
// Пытаемся сохранить запись в базе
......@@ -54,16 +59,17 @@ class DefaultController extends BaseController
// Коммитим транзакцию
$transaction->commit();
// Возвращаем результат
return ['success' => true];
$result['result'] = true;
} else {
// В противном случае возвращаем форму с ошибками
return ActiveForm::validate($model);
$result['error'] = current(current($model->getErrors()));
}
} catch (\Exception $e) {
// Обрабатываем исключение
$transaction->rollBack();
throw $e;
$result['error'] = $e->getMessage();
}
echo Json::encode($result);
} else {
// Если это не ajax запрос, возвращаем ошибку
throw new NotFoundHttpException('The requested page does not exist.');
......
......@@ -42,10 +42,10 @@ if ($cacheEmail!==false && CasesBids::find()->where(['email' => $cacheEmail])->e
'template' => '<div class="row"><div class="col-sm-4">{input}</div></div>',
'errorOptions' => []
])->textInput([
'placeholder' => 'E-mail*'
'placeholder' => 'E-mail*',
]); ?>
<?php echo Html::submitButton(\Yii::t('form', 'Subscribe'), ['class' => 'save-button']); ?>
<?php echo Html::button(\Yii::t('form', 'Subscribe'), ['class' => 'save-button']); ?>
</div>
......@@ -55,86 +55,35 @@ if ($cacheEmail!==false && CasesBids::find()->where(['email' => $cacheEmail])->e
</div>
<script type='text/javascript'>
$('form.keys_mail_form').on('beforeSubmit', function(e) {
var form = $(this), xhr = new XMLHttpRequest, filebool = false, file, data = new FormData();
form.find('input, textarea').each(function(){
data.append($(this).attr('name'), $(this).val());
});
xhr.open("POST", form.attr('action'), true);
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhr.send(data);
xhr.onreadystatechange = function()
{
if (xhr.readyState == 4){
try {
var response = JSON.parse(xhr.responseText);
} catch(e) {
var response = xhr.responseText;
}
form.find('.has-error').removeClass('has-error');
if(response.success) {
if(form.find('.message-box.send_secce').length > 0) {
form.find('.message-box.send_secce').fadeIn('fast');
form.find('.content').css('visibility','hidden');
setTimeout(function(){
form.find('.message-box.send_secce').fadeOut('fast');
form.find('.content').css('visibility','visible');
}, 2000);
}
form.find('input:not(.not_clear), textarea').val('');
form.find('#files-zone').html('');
$('.dz-preview.dz-processing').remove();
dataLayer.push({
'event': 'UA_event',
'Catagory': form.data('tag'),
'Action': form.data('title'),
'Label': 'Успешно'
});
setInterval(function() {
form.parent('div').fadeOut(500);
}, 1600);
}
else {
var errors = [];
$.each(response, function(key, value) {
form.find('.field-'+key).addClass('has-error');
errors = errors.concat(value);
});
console.log(errors);
if(form.find('.message-box.send_err').length > 0)
{
form.find('.message-box.send_err').html(errors[0]);
form.find('.message-box.send_err').fadeIn('fast');
setTimeout(function(){
form.find('.message-box.send_err').fadeOut('fast');
}, 2000);
}
dataLayer.push({
'event': 'UA_event',
'Catagory': 'Ошибки',
'Action': form.data('form'),
'Label': errors
});
$('.save-button').on('click', function() {
var form = $(this).closest('form');
var email = form.children('input[name="CasesBids[email]"]').val();
$.ajax({
url: form.attr('action'),
data: {
email: email
},
method: 'GET',
success: function(response) {
var result = JSON.parse(response);
if (result.result==true) {
form.find('.message-box.send_secce').fadeIn('fast');
form.find('.content').css('visibility','hidden');
setTimeout(function(){
form.find('.message-box.send_secce').fadeOut('fast');
form.find('.content').css('visibility','visible');
}, 2000);
} else {
form.find('.message-box.send_err').html(result.error);
form.find('.message-box.send_err').fadeIn('fast');
setTimeout(function(){
form.find('.message-box.send_err').fadeOut('fast');
}, 2000);
}
}
}
}).on('submit', function(e){
return false;
});
});
</script>
<?php endif; ?>
\ No newline at end of file
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment