How to call Ajax function and Controller Action

I’m new to programming, and I’m trying to call a function when the user imputs 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) {

          console.log(data.search);

       }

  });

    }

</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()

{

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,

    ];

  }

}



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!