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:



    function myFunction()



       url: '<?php echo Yii::$app->request->baseUrl. '/supermarkets/sample' ?>',

       type: 'post',

       data: {searchname: $("#searchname").val() , searchby:$("#searchby").val()},

       success: function (data) {







use yii\helpers\Html;

use yii\widgets\LinkPager;




<select id="searchby">

    <option value="" disabled="disabled" selected="selected">Search by</option>

    <option value="Name">Name</option>

    <option value="Location">Location</option>


<input type="text" value ="" name="searchname", id="searchname">

<button onclick="myFunction()">Search</button>

<h3> </h3>


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!