PHP code example of srv44 / yii2-ajax-actions-behavior

1. Go to this page and download the library: Download srv44/yii2-ajax-actions-behavior library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

srv44 / yii2-ajax-actions-behavior example snippets


use srv44\AjaxActions\AjaxActionsBehavior;

...

public function behaviors()
{
    return [
        ...
        AjaxActionsBehavior::className(),
    ];
}

use srv44\AjaxActions\AjaxActionsBehavior;

...

public function behaviors()
{
    return [
        ...
        [
            'class' => AjaxActionsBehavior::className(),
            'checkResponse' => false
        ],
    ];
}

...

...

public function actionAjaxYourAction() 
{
    ...
}

...

...

public function actionAjaxYourAction() 
{
    return 'some value';
}
// result: 'some value'

...

...

public function actionAjaxYourAction() 
{
    return ['success' => true, 'your' => 'value'];
}
// result: {"success":true,"your":"value"}

...

use srv44\AjaxActions\AjaxActionsHelper;

...

// without params
public function actionAjaxWithoutParams() 
{
    return AjaxActionsHelper::success();
}
// result: {"success":true}

// with params
public function actionAjaxWithParams() 
{
    return AjaxActionsHelper::success(['your' => 'value']);
}
// result: {"success":true}

...

use srv44\AjaxActions\AjaxActionsHelper;

...

// Without params
public function actionAjaxWithoutParams() 
{
    return AjaxActionsHelper::error();
}
// result: {"success":false, "errorMessage":"Error!"}

// Only error message
public function actionAjaxOnlyErrorMessage() 
{
    return AjaxActionsHelper::error('Bad request!');
}
// result: {"success":false, "errorMessage":"Bad request!"}

// With error message and params
public function actionAjaxWithErrorMessageAndParams() 
{
    return AjaxActionsHelper::error('Bad request!', ['your' => 'value']);
}
// result: {"success":false, "errorMessage":"Bad request!", "your" => "value"}

// With custom error message field
public function actionAjaxWithCustomErrorField() 
{
    return AjaxActionsHelper::error('Bad request!', ['your' => 'value'], 'myErrorMessage');
}
// result: {"success":false, "myErrorMessage":"Bad request!", "your" => "value"}

...