как запустить таймер обратного отсчета без обновления страницы и обновить статус записи с помощью действия в yii2 - PullRequest
0 голосов
/ 08 октября 2019

Что я хочу сделать? Я хочу создать вопрос с таймером обратного отсчета ajax, который загружается нажатием клавиши Shift и загружается без обновления страницы, а также обновляет статус этого вопроса. после завершения таймера он должен перенаправить на другую страницу, но без обновления страницы.

что я делаю? Я показываю вопрос с опциями, у него есть таймер обратного отсчета, он начинается сНажатие правой кнопки сдвига после нажатия кнопки сдвига обновляет страницу и через 20 секунд перенаправляет на результат вопросов. (главная проблема - обновление страницы, я хочу этого избежать)

Моя кодировка

allvoting.php

<?php

use yii\helpers\Html;
use yii\widgets\DetailView;
use yii\widgets\ActiveForm;
use yii\widgets\LinkPager;
use yii\helpers\Url;
use yii\widgets\Pjax;
// use \stmswitcher\stmswitcher\flipclock\FlipClock;


/* @var $this yii\web\View */
/* @var $voting app\models\Voting */

?>
<script type="text/javascript" src="js/jquery.js"></script>
<style type="text/css">

    .timerStrip {
    background: url(images/timer-strip-13.jpg);
    width: 900px;
    height: 79px;

    background-repeat: no-repeat;
}



.bbttons{
  margin: 0 2px -39px 0; 
  opacity:0.1;
}

.main-header {
    position: relative;
    max-height: 100px;
    z-index: 1030;
    background: #FFFFFF !important;
}




</style>


<div id="wholewrapper" style="margin: 2% auto 0 auto; width: 60%;">
<div class="row">

<div class="row">

        <?php foreach ($voting as $key){ ?>

        <h1 class="votqts"><?php echo 'Q: '.$key->question; ?></h1>

</div>






<?php 
if (Yii::$app->session->hasFlash('timer')){ ?>

<audio controls autoplay preload="metadata" style="display:none">
    <source src='../web/sounds/timer.mp3' type='audio/mpeg'>

</audio>

  <div id="timer" class="alert alert-danger">
  <button aria-hidden="true" data-dismiss="alert" class="close" type="button">×</button>
  <h4><i class="fa fa-clock-o fa-2x" aria-hidden="true"></i><?= '  '


  . Yii::$app->session->getFlash('timer')

  . \russ666\widgets\Countdown::widget([
    'datetime' => date('Y-m-d H:i:s O', time() + 20),
    'format' => '%M:%S',
    'events' => [
        'finish' => 'function(){location.replace("'.Url::toRoute(['voting/reset','id'=>$key->q_id]).'")}',
    ],
]); 
?></h4>

  </div>

<?php } else { ?>
    <div id="timer" class="alert alert-danger">
          <button aria-hidden="true" data-dismiss="alert" class="close" type="button">×</button>
          <h4><i class="fa fa-clock-o fa-2x" aria-hidden="true"></i> you have 20 seconds <span id="w0">00:20</span></h4>

    </div>
<?php } ?>  

 <div class="col-md-12">

        <div class="row allqOption">
            <?php if($key->option1!==''){?>

                <span class="numbspn">1</span>

                <p class="numbpr"><?= $key->option1 ?></p>

            <?php } ?>
         </div>   


         <div class="row allqOption">
            <?php if($key->option2!==''){?>

                <span class="numbspn">2</span>

                <p class="numbpr"><?= $key->option2 ?></p>

            <?php } ?>
         </div> 


         <div class="row allqOption">
            <?php if($key->option3!==''){?>

                <span class="numbspn">3</span>

                <p class="numbpr"><?= $key->option3 ?></p>

            <?php } ?>
         </div> 


         <div class="row allqOption">
            <?php if($key->option4!==''){?>

                <span class="numbspn">4</span>

                <p class="numbpr"><?= $key->option4 ?></p>

            <?php } ?>
         </div> 


         <div class="row allqOption">
            <?php if($key->option5!==''){?>

                <span class="numbspn">5</span>

                <p class="numbpr"><?= $key->option5 ?></p>

            <?php } ?>
         </div> 

         <div class="row allqOption">
            <?php if($key->option6!==''){?>

                <span class="numbspn">6</span>

                <p class="numbpr"><?= $key->option6 ?></p>

            <?php } ?>
         </div> 
        </div>

</div>

</div>
<div class="row bbttons">
    <?php Pjax::begin([
        'id' => 'comments-pjax',
        'enablePushState' => false,
        'formSelector' => '#timer_submit_form'
    ]); ?>
    <div style="width: 20%; float:right;">
        <?php $form = ActiveForm::begin(['action' =>['voting/timer'], 'id' => 'timer_submit_form', 'method' => 'post']); ?>
        <?php ActiveForm::end(); ?> 
    </div>   
    <?php Pjax::end(); ?>
</div> 



<script>
setTimeout(function() {
            $('#timer').fadeOut('fast');
            }, 20000); 

$(document).keydown(function (event) {
  var key = "<?php echo $key->q_id ?>";

    if (event.keyCode == '39') { // right-arrow. it is showing the result of the question
        window.location.href = "https://localhost/myprject/backend/web/index.php?r=voting%2Fvotingresults&q_id="+key;
    }
});

$(document).keydown(function (event) {
  var key = "<?php echo $key->q_id ?>";

    if (event.keyCode == '16') {
        window.location.href = "https://localhost/myprject/backend/web/index.php?r=voting%2Ftimer&id="+key;
    }
});

//First question with key 1
$(document).keydown(function (event) {

    if (event.keyCode == '97') {
        window.location.href = "https://localhost/myprject/backend/web/index.php?r=voting/allvoting";
    }
});


//second question with key 2
$(document).keydown(function (event) {

    if (event.keyCode == '98') {
        window.location.href = "https://localhost/myprject/backend/web/index.php?r=voting/allvoting&page=2&per-page=1";
    }
});



</script>

<?php } ?>
</div>

VotingController.php

<?php

namespace backend\controllers;

use Yii;
use common\models\Voting;
use common\models\VotingSearch;
use common\models\VotingOptions;
use common\models\VotingResponse;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\db\Expression;
use yii\data\Pagination;
/**
 * VotingController implements the CRUD actions for Voting model.
 */
class VotingController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

public function actionTest()
{
  return $this->render('test');

}
    /**
     * Lists all Voting models.
     * @return mixed
     */
    public function actionIndex()
    {
      $this->layout = 'voting_layout';
        $searchModel = new VotingSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single Voting model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
      $this->layout = 'voting_layout';
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }





    /**
     * Deletes an existing Voting model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the Voting model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Voting the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Voting::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }


    public function actionTesting()
    {
        return $this->render('testing');
    }


    public function actionTimer($id)
    {

        $model = $this->findModel($id);
        Voting::updateAll(['timer' => 0], 'timer = 20');

        if($model->timer!==20){
            $model->timer=20;
            $model->save(false);

           } else {

            return "you have already submitted this question";
            return false;
           }

        \Yii::$app->getSession()->setFlash('timer', '   '.'Please Vote the Question, you have 20 seconds');    
        return $this->redirect(Yii::$app->request->referrer);
    }


    public function actionAllvoting()
    {
      $this->layout = 'voting_layout';
      Yii::$app->view->title = 'Voting';
        /* code for pagination starts */

        $query = Voting::find()->orderBy([

        'q_id'=>SORT_ASC
    ]);
        $count = $query->count();       
        $pagination = new Pagination(['totalCount' => $count, 'pageSize'=>1]); 

        /* code for pagination ends */

        // $voting = $query->offset($pagination->offset)
        //     ->limit($pagination->limit)
        //     ->with('votingOption')
        //     ->all();

        $voting = $query->offset($pagination->offset)
            ->limit($pagination->limit)
            ->all();

        return $this->render('allvoting',[
          'voting'=>$voting,
          'pagination'=>$pagination]);  


    }


    public function actionVotingresults($q_id)
    {
        $this->layout = 'voting_layout';

        $question = Voting::find()->where(['q_id'=>$q_id])->one();
        $result = VotingResponse::find()->where(['q_id'=>$q_id])->all();
        $count = VotingResponse::find()
        ->where(['q_id'=>$q_id])
        ->count();


        // $total = Yii::$app->db->createCommand('SELECT COUNT(*) as count FROM voting_response WHERE ')
        //     ->queryAll();

        return $this->render('votingresutls',[
            'question' => $question,    
            'result'=> $result,
            'count' => $count
            ]); 

    }


    public function actionReset($id){

        $model = $this->findModel($id);
        Voting::updateAll(['timer' => 0], 'timer = 20');

        if($model->timer!==0){
            $model->timer=0;
            $model->save(false);

           } 
        return $this->redirect(['votingresults', 'q_id' => $model->q_id]);

    }
}

мой код работает нормально, но он обновляет страницу, когда я нажимаю кнопку сдвига, чтобы запустить таймер обратного отсчета, и секунду, когда он перенаправляетстраница результатов. Я хочу избежать обновления страницы. Пожалуйста помоги. Заранее большое спасибо.

...