2

Im developing a search bar in yii2 using ajax. The problem is the Yii::$app->request->isAjax property always returns false

This is my action:

public function actionAjaxsearch()
{   
    if(Yii::$app->request->isAjax)
    {   
        $keywords = Yii::$app->request->queryParams;
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        return [
            'data' => $keywords,
            'code' => 200
        ];
    }
    else throw new \yii\web\HttpException(404, 'Page not found.');

And this is my script:

$('#search-box').keyup(function( event ){
    event.preventDefault();     
    $.ajax({
        url: 'http://localhost/items/ajaxsearch',
        data: {keywords: $( '#search-box' ).val()},
        type: 'GET',
        dataType: 'json',
    }).done(function(){
        console.log('success');
    }).fail(function( data ){
        alert( data );
    }).always(function(){
        alert('finished');
    })
});

If i dont use the if with Yii::$app->request->isAjax the controller just render the JSON with the data.

P.D The content of #search-box is succesfully passed.

Edit to @SilverFire

Dont have some in the dump

["HTTP_X_REQUESTED_WITH"] => not defined,
["HTTP_ACCEPT"]=> string(74) "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
["CONTENT_TYPE"] =>not defined,
["HTTP_CONTENT_TYPE"] =>not defined,
["REQUEST_METHOD"]=> string(3) "GET",
["HTTP_X_HTTP_METHOD_OVERRIDE"] =>not defined,
Sageth
  • 1,102
  • 1
  • 15
  • 30

1 Answers1

4

Well, your browser for some reasons does not send the HTTP_X_REQUESTED_WITH headers to the server.

It guess it might be related to: Missing X-Requested-With: XMLHttpRequest (causes 200 OK But Shows as Error?) and Cross-Domain AJAX doesn't send X-Requested-With header

Community
  • 1
  • 1
SilverFire
  • 1,582
  • 13
  • 22
  • I've tried to add the `X-Requested-With` header in the ajax request but still doesn't work. – Sageth Dec 09 '15 at 14:01
  • Do you see this header on PHP side after you've added it in the ajax request? – SilverFire Dec 09 '15 at 14:06
  • It's the only way how server could guess that it's an Ajax request, so the problem relates at most XHR requests. Could you show a screenshot or text dump from the browser debug console with the detailed info about the request? – SilverFire Dec 09 '15 at 14:56