3

I have an AJAX call in my view to an action in my controller. However, I always get an Error 400. Below is the code for my AJAX call:

    $.ajax({
        cache: false,
        url: '/dummy/index.php/module/controller/checkCross',
        dataType: 'json',
        type: 'POST',
        data : {"male":parents[0],"female":parents[1]},
        success: function(result){
            alert(result);
        }
    });

Below is the code in the controller:

 public function actionCheckCross(){

     if(Yii::app()->request->isPostRequest) { // check if POST
        $flag = CrossingMatrix::model()->checkParentsIfCrossed($_POST['male'],$_POST['female']);

        if($flag){
            return true;
        }

        else{
            return false;
        }

    } else { // direct URL request will be GET, so show error
        throw new CHttpException(400, Yii::t('app', 'Direct access is not allowed.'));
    }

}

Any ideas?

jackeblagare
  • 407
  • 7
  • 21
  • Try to `dump_var` before `isPostRequest` check. And manually check url `/dummy/index.php/module/controller/checkCross` – b1_ May 02 '13 at 09:03
  • I tried doing a var_dump and all variables are properly passed. After the var_dump, the error 'Your request is invalid.' pops up again. – jackeblagare May 02 '13 at 09:07

1 Answers1

2

You are expecting json data, but you send empty page to browser. You should encode result like that:

echo CJavascript::jsonEncode((bool)$flag);
Yii::app()->end();

In your code you returned value. Notice that your yii exception message is Direct access is not allowed but your error is Your request is invalid.

  • Hmm, while your observations are true, how does this explain the 400 error? – Michael Härtl May 02 '13 at 10:13
  • This comes from jquery, as response was not json –  May 02 '13 at 10:14
  • That quite surprises me. The status code is part of the response header. In the case above the server did not send any 400. So you say, jQuery gives a "false" response code of 400 even if the server returns 200? Is this documented somewhere? – Michael Härtl May 02 '13 at 10:19
  • I just did a little test and could not verify this. You get some clientside error if you don't return JSON, but never a 400. So I think, it was something else that caused the 400. – Michael Härtl May 02 '13 at 10:35
  • You right, even if json response is invalid status remains 200, so source of this 400 header is something else. –  May 02 '13 at 10:53
  • Maybe there was also some issue with data param, here is some answer about it http://stackoverflow.com/a/16054639/133408 –  May 02 '13 at 11:03