yii2fetch-apiyii2-advanced-app

How to use fetch API for calling a YII2 Controller method


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?


Solution

  • 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);
        });