Yii Framework 2.0 check if it is a GET request from AJAX

Working with Yii framework 2.0, I have an AJAX GET jQuery script that points to a function in a controller class.

$.get('localhost/website/index', {param: 'xxxx'}, function(returnedData){
    // some code here.....
}, 'json');

      

In the controller class, I have the following method that handles the AJAX GET request.

public function actionIndex() {
     $getParam = $_GET['param'];
     // echo $getParam is: 'xxxx'.

     // some other code here....

     echo json_encode(array());
}

      

Everything works fine when executing this AJAX GET jQuery script. But if I go to the localhost / website / index link manually in a web browser, I get the following error.

PHP Notice - ErrorException
Undefined index: param

// the code snippet is also being shown.....

      

I don't want users to see this error if they know this link and accidentally visit this link by accident or on purpose. If i use

if($_GET['param']){...}

      

I am still getting the error in the browser. How can I solve this?

+3


source to share


2 answers


You can check that the request is an ajax request:

$request = Yii::$app->request;
if ($request->isAjax) {...}

      

Or you can check that the POST or GET request



if (Yii::$app->request->isPost) {...}
if (Yii::$app->request->isGet) {...}

      

And always use isset ()! :)

+11


source


easy way:

if (isset($_GET['param'])) {
    ...
}

      



the right way:

if (isset($_SERVER['HTTP_X_REQUESTED_WITH'] 
    && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')
) {
    //...
}

      

+1


source







All Articles