0

i have a table in my view and having <tbody id="tableckp"></tbody> as the table body.

next, i have a button to add a row in the table using ajax, the id is 'tomboltambah'.

as mentioned above, i'm using Yii2, so i need to pass the data to the controller of the app. I am not sure how i should fill the url parameter in the ajax. After browsing in the internet for hours, here are my code: (still get the same error: 400)

The ajax, jquery (included using an asset):

$(document).ready(function() {

$('#example1').DataTable();
$('#tomboltambah').click(function(){
    var request = $.ajax({
      url: "tomboltambah",
      type: "POST",
      data: {"tambah" : '1', "_csrf" : '<?=Yii::$app->request->getCsrfToken()?>'},
      dataType: "html"
    });

    request.done(function(msg) {
      $("#tableckp").append(data);
    });

    request.fail(function(jqXHR, textStatus) {
      alert( "Request failed: " + jqXHR.status );
    });
});
});

And here is my controller (it is in MainController):

 public function actionTomboltambah() {
    return 
            '<tr>
                <td></td>
                <td></td>
                <td></td>
                <td></td>
                <td></td>
                <td></td>
                <td></td>
            </tr>';
}

I think the url is righ (because it is error code 400, if the url is the problem it should be 404 bad request, right?).

Can anyone find the problem here? thanks for your time, hope you have a good day, i've been searching for hours!

This is the config file requested:

$params = require __DIR__ . '/params.php';
$db = require __DIR__ . '/db.php';

$config = [
    'id' => 'absensi',
    'basePath' => dirname(__DIR__),
    'bootstrap' => ['log'],
    'defaultRoute' => 'main/index',
    'aliases' => [
        '@bower' => '@vendor/bower-asset',
        '@npm'   => '@vendor/npm-asset',
    ],
    'components' => [
        'request' => [
            // !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
            'cookieValidationKey' => 'widfJPdqz5vq3a764eRz_ID7duHl_WtW',
        ],
        'cache' => [
            'class' => 'yii\caching\FileCache',
        ],
        'user' => [
            'identityClass' => 'app\models\User',
            'enableAutoLogin' => true,
        ],
        'errorHandler' => [
            'errorAction' => 'site/error',
        ],
        'mailer' => [
            'class' => 'yii\swiftmailer\Mailer',
            // send all mails to a file by default. You have to set
            // 'useFileTransport' to false and configure a transport
            // for the mailer to send real emails.
            'useFileTransport' => true,
        ],
        'log' => [
            'traceLevel' => YII_DEBUG ? 3 : 0,
            'targets' => [
                [
                    'class' => 'yii\log\FileTarget',
                    'levels' => ['error', 'warning'],
                ],
            ],
        ],
        'db' => $db,

        'urlManager' => [
            'showScriptName' => false,
            'enablePrettyUrl' => true,
        ],
        /*
        'urlManager' => [
            'enablePrettyUrl' => true,
            'showScriptName' => false,
            'rules' => [
            ],
        ],
        */
    ],
    'params' => $params,
];

if (YII_ENV_DEV) {
    // configuration adjustments for 'dev' environment
    $config['bootstrap'][] = 'debug';
    $config['modules']['debug'] = [
        'class' => 'yii\debug\Module',
        // uncomment the following to add your IP if you are not connecting from localhost.
        //'allowedIPs' => ['127.0.0.1', '::1'],
    ];

    $config['bootstrap'][] = 'gii';
    $config['modules']['gii'] = [
        'class' => 'yii\gii\Module',
        // uncomment the following to add your IP if you are not connecting from localhost.
        //'allowedIPs' => ['127.0.0.1', '::1'],
    ];
}

return $config;
Luckatme
  • 9
  • 6
  • 400 Bad Request: _"The request could not be understood by the server due to malformed syntax. The client SHOULD NOT repeat the request without modifications."_ – Andreas Aug 28 '18 at 06:28
  • @Andreas so, what should i do? i am new with yii2 – Luckatme Aug 28 '18 at 06:30
  • Check the request in the network tab of the developer tools and compare the format with the expected format/parameters of the server and fix any errors – Andreas Aug 28 '18 at 06:31
  • in your browser (`ctrl+shif+i` chrome ff) developer tools -> network -> XHR and look for your request, there will be response with error description – Edgarth Aug 28 '18 at 06:34
  • Why are you using ajax if you only want to append row? You can send a request to the server and get data from there and simply append row using jQuery. – akshaypjoshi Aug 28 '18 at 06:38
  • are you using the `advance` or `basic-app` for yii2, plus is the name defined as `_csrf` for the `csrfParam` under the request component in the config ? – Muhammad Omer Aslam Aug 28 '18 at 06:40
  • @Edgarth here is Bad Request (#400): Unable to verify your data submission. – Luckatme Aug 28 '18 at 06:41
  • @akshaypjoshi hey man, i think you are right haha. oh i've been searching for hours. But how if in the future i need to make an ajax request – Luckatme Aug 28 '18 at 06:42
  • @Luckatme read about CSRF tokens, i don't know yii but this can be your problem – Edgarth Aug 28 '18 at 06:43
  • @MuhammadOmerAslam i am using the basic bro. about the _csrf params, i dunno, i think not. what should i do? – Luckatme Aug 28 '18 at 06:44
  • can you add your `config/web.php` in your question by editing. – Muhammad Omer Aslam Aug 28 '18 at 06:47
  • @MuhammadOmerAslam done bro, check it out. thanks for your time anyway – Luckatme Aug 28 '18 at 07:09

2 Answers2

0

You can use this JS to send a request and get data from MainController and append row like this

$('#tomboltambah').click(function(){
    $.post("/main/tomboltambah", {'tambah': '1'}, function (response, status) {
        var data = $.parseJSON(response);
        var yourHTML = "";

        yourHTML = "<tr><td>" + data["key1"] + "</td><td>" + data["key2"] + "</tr>";

        $("#tableckp").html(yourHTML);
    });
});

MainController :

public function actionTomboltambah() {
    ...
    ...
    ...
    $someData = [...];
    return json_encode($someData);
}
akshaypjoshi
  • 1,245
  • 1
  • 15
  • 24
0

First make sure that tokens are equal. They can not be equal according to your code. Use the native Yii js decision

data: {"tambah" : '1', "_csrf" : yii.getCsrfToken()},

To exclude csrf protection, that returns 400 header you can disable it for debug reasons in your controller Disable CSRF validation for individual actions in Yii2

Secondary, your rules are empty, and reference to ajax request is tomboltambah, but controller MainController::actionTomboltambah(), so it must be main/tomboltambah

Thirdly (the main) Your code is pretty strange. You want to use js lib, but return pure html into the view file. This is a bad practice.

  • `=Yii::$app->request->getCsrfToken()?>` will also work inside the `.php` files you use the Yii Js for the code used in the `.js` files,where PHP tags `=?>` wont work otherwise its the same. But the answer OP has selected does not seem to be fixing the `400 Bad Request` but works for OP anyway. what i suspected in start was that he must be using some other name for the `csrfParam`. – Muhammad Omer Aslam Aug 28 '18 at 11:53