E
E
Eugene2018-02-23 09:33:58
Yii
Eugene, 2018-02-23 09:33:58

How to properly handle Ajax in Yii2?

In general, I made it so that on an event (Date change) Ajax sends this date to the server.

javascript
$(function () {

    $('#datetimepicker1').datetimepicker(
        {format: 'DD.MM.YYYY', locale: 'ru'}


  );

    $('#datetimepicker1').on("dp.change", function ()
    {

        var bes = $(".form-control").val()

        $.ajax(
            {
                url:window.location,
                data: {a:bes},
                type: 'POST',
                success: function (res) {
                    console.log(res);
                },
                error:function () {
                    alert('Error');
                }
            }
        );
    });
});

Now I need to process this value and return an array
I thought to do it like this
Controller
class CategoryController extends Controller
{
    public function actionViewdoc($id=null)
    {
        $id = Yii::$app->request->get('id');

       if (Yii::$app->request->isAjax && Yii::$app->request->isPost)
       {
           $carddoc = Yii::$app->request->post('a');
           return Cards::find()->where(['doctor_id' =>$id],['data' =>$carddoc)->asArray()->all();
       }




        $doc = Doctor::find()->where(['id' =>$id])->asArray()->all();

        return $this->render('viewdoc' ,compact('doc'));

    }
}

But that doesn't work. What am I doing wrong? I need to select data based on data from ajax. And return an array. In my case, an array of coupons

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Arman, 2018-02-23
@Arik

POST should change the state of the application, why are you asking for data through it? GET is better here

if (Yii::$app->request->isAjax && Yii::$app->request->isPost) {
    $carddoc = Yii::$app->request->post('a');
    $cards = Cards::find()->where(['doctor_id' => $id, 'data' => $carddoc])->asArray()->all();
    return $this->asJson($cards);
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question