How to use fetch API for calling a YII2 Controller method

60 Views Asked by At

I want to make an Ajax call to a Controller method.

fetch(url, {
            //method: 'GET',
            //body: dati,
            //headers: {
                //'Content-type': 'application/x-www-form-urlencoded'
            //}
        }).then(function (response) {
            if (response.ok) {
                return response;
            }else{
                return Promise.reject(response);
            }
            
        }).then(function (data) {
            console.log(data);

        }).catch(function (error) {
            console.warn('Something went wrong.', error);
        });

url is

cart/update-cart?id=13&action=add

This is my controller code

public function actionupdateCart(int $id, string $action){
    if (Yii::$app->request->isAjax) {
        return json_encode('Ajax call');

    }else{
        return json_encode('Not Ajax call?');
    }

I expect the result: 'Ajax call' instead i get 'Not Ajax call?' Why isAjax is set to false?

2

There are 2 best solutions below

0
Sfili_81 On BEST ANSWER

I've solved forcing header when calling fetch API:

fetch(url, {
        method: 'GET',
        headers: {
            'X-Requested-With': 'XMLHttpRequest'
        }
    }).then(function (response) {
        if (response.ok) {
            return response.json();
    }else{
            return Promise.reject(response);
        }
        
    }).then(function (data) {
        console.log(data);

    }).catch(function (error) {
        console.warn('Something went wrong.', error);
    });
0
Evgeny On

To determine the ajax request, Yii2 uses the headers->get('X-Requested-With') === 'XMLHttpRequest' check. When using fetch, there is no such header. You need to fix it to $.ajax for the check to work.