简体   繁体   中英

Ajax + Controller Action in Yii2

I'm new to programming, and I'm trying to call a function when the user inputs data and clicks submit button. I'm using Yii2 and I'm not familiar with Ajax. I tried developing a function, but my controller action isn't called.

Here is the example code I'm trying:

views/index.php:

<script>
    function myFunction()
    {
        $.ajax({
            url: '<?php echo Yii::$app->request->baseUrl. '/supermarkets/sample' ?>',
           type: 'post',
           data: {searchname: $("#searchname").val() , searchby:$("#searchby").val()},
           success: function (data) {
              alert(data);

           }

      });
    }
</script>

<?php
use yii\helpers\Html;
use yii\widgets\LinkPager;

?>
<h1>Supermarkets</h1>
<ul>

<select id="searchby">
    <option value="" disabled="disabled" selected="selected">Search by</option>
    <option value="Name">Name</option>
    <option value="Location">Location</option>
</select>

<input type="text" value ="" name="searchname", id="searchname">
<button onclick="myFunction()">Search</button>
<h3> </h3>

Controller:

public function actionSample(){         
     echo "ok";
}

My problem is that when I click on the Search button nothing happens, and when I try to debug it, the debugger runs no code!

This is sample you can modify according your need

public function actionSample()
{
if (Yii::$app->request->isAjax) {
    $data = Yii::$app->request->post();
    $searchname= explode(":", $data['searchname']);
    $searchby= explode(":", $data['searchby']);
    $searchname= $searchname[0];
    $searchby= $searchby[0];
    $search = // your logic;
    \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
    return [
        'search' => $search,
        'code' => 100,
    ];
  }
}

If this will success you will get data in Ajax success block. See browser console.

  $.ajax({
       url: '<?php echo Yii::$app->request->baseUrl. '/supermarkets/sample' ?>',
       type: 'post',
       data: {
                 searchname: $("#searchname").val() , 
                 searchby:$("#searchby").val() , 
                 _csrf : '<?=Yii::$app->request->getCsrfToken()?>'
             },
       success: function (data) {
          console.log(data.search);
       }
  });

you have to pass _csrf tokin as a parameter

_csrf: yii.getCsrfToken()

or you can disable csrf valdation

获得CSRF参数的正确方法是:

data[yii.getCsrfParam()] = yii.getCsrfToken()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM