Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 799
user3640056 Avatar asked Mar 03 '15 12:03

user3640056


2 Answers

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);
       }
  });
like image 86
ankitr Avatar answered Sep 18 '22 01:09

ankitr


you have to pass _csrf tokin as a parameter

_csrf: yii.getCsrfToken()

or you can disable csrf valdation

like image 45
Abdallah Awwad Alkhwaldah Avatar answered Sep 22 '22 01:09

Abdallah Awwad Alkhwaldah