Viskas
Viskas

Reputation: 135

Yii2 trouble with Ajax request

Hello everybody! Please help me to solve the problem.

I have some html

<ul class="filter_list filter_house_type">
      <li><input type="checkbox" id="check1" value="House" onclick="sendRequest();"><label for="check1"><?= Yii::t('app', 'House') ?></label></li>
</ul>

js

function sendRequest(){
   $.ajax({
       url: '/site/ajax',
       type: 'POST',
       data: { text: 'text' },
       success: function(data) {
           alert(data);
       }
   });
}

Controller action

public function actionAjax()
{
    if(Yii::$app->request->post('text')){
        $test = 'Ajax request';
    } else {
        $test = 'Some troubles!';
    }
    return \yii\helpers\Json::encode($test);
}

When I click on the checkbox i see a page with "Some troubles!" and console is empty.
enter image description here Why rendering page? How can I get an answer in Ajax function. Please, help!

Upvotes: 0

Views: 934

Answers (1)

ScaisEdge
ScaisEdge

Reputation: 133360

could be you need a check on post('text') eg:

  public function actionAjax()
  {
      $post = Yii::$app->request->post()
      if(isset($post('text')){
          $test = 'Ajax request';
      } else {
          $test = 'Some troubles!';
      }
      return \yii\helpers\Json::encode($test);
  }

and try using method POST instead of type

$.ajax({
   url: '/site/ajax',
   method: 'POST',
   data: { text: 'text' },
   success: function(data) {
       alert(data);
   }

});

and just for debugging purpose try using a differente approach

use post instead of ajax ,.. test instead of text

$.post( '/site/ajax' , {test:'test'},
    function (data) { 
        alert(data);
 });

.

public function actionAjax()
{
    if(Yii::$app->request->post('test')){
        $test = 'Ajax request';
    } else {
        $test = 'Some troubles!';
    }
    return \yii\helpers\Json::encode($test);
}

Upvotes: 1

Related Questions