S
S
Sergey Gladyshev2016-10-16 15:16:53
Yii
Sergey Gladyshev, 2016-10-16 15:16:53

Why doesn't AJAX work in Yii2?

Yii2. There is a form with two fields. The data from this form is sent by ajax request to the controller, but as a result 404 is returned.
Script code:

if ( $scope.form.$valid ) {
            $http.post( '/site/githublogin/', $scope.user ).success(function( res ){
        alert(res.res);
                if ( res.res=='ok') {
                    $scope.user = {};
                    $scope.form.$setPristine();
                    $scope.greeting = "Авторизация успешна";
                } else {
                    $scope.greeting = "Ошибка авторизации. Неверное имя пользователя или пароль.";
                }
            }).error(function(err){
                $scope.greeting = err;
            });
        }


Controller:
public function actionGithublogin()
    {
    
    
    $res = array( 'res'=>'ok' );
        echo json_encode($res);
    
    }


If you open the /site/githublogin/ page in a browser, then everything is fine, {"res":"ok"} is displayed.
csrf off
'components' => [
        'request' => [
            // !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
            'cookieValidationKey' => 'DSFgksdifhiw899734hekfDFGisjdfi9374',
      'enableCsrfValidation' => false,
        ],


What could be the problem ? Which way to dig? New to Yii2.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Maxim Timofeev, 2016-10-24
@webinar

It's probably because you didn't send the CSRF token. Therefore, with a get request, everything works, but with a post request, an error occurs, since the transmitted data did not pass the test. You must either add a token to the CSRF request or disable its verification for this action. Details here: www.fantomslim.ru/articles/yii2-ispolzovanie-csrf-...

S
Sergey Gladyshev, 2016-10-16
@Resident234

$http.post( ' localhost/uprock2/site/githublogin ', $scope.user ).success(function( res ){
- worked like this. got it. Calculate the site address ( localhost/uprock2) and substitute it before /site/githublogin /
thank you all.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question